Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Compress the captured image file size before sending to server using retrofit

I am Using Retrofit retrofit:2.1.0' to upload file image to server

If I take image using front camera image get uploaded successfully but if take back side camera its not uploaded i think because of large file size image not uploaded is there any option to compress the file size before sending to server in retrofit?

File Sending Coding

  map.put("complaint_category", RequestBody.create(parse("text"), caty_id_str.getBytes()));

    // Map is used to multipart the file using okhttp3.RequestBody
    File file = new File(Config.uriImage);
    // Parsing any Media type file
    RequestBody requestBody = RequestBody.create(parse("*/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("photo", file.getName(), requestBody);
    RequestBody filename = RequestBody.create(parse("text/plain"), file.getName());

    Call<PostComplaint> call3 = apiInterface.postComplaint(fileToUpload, filename, map);
    call3.enqueue(new Callback<PostComplaint>() {
        @Override
        public void onResponse(Call<PostComplaint> call, Response<PostComplaint> response) {

            progressDoalog.dismiss();

            PostComplaint respon = response.body();

            PostComplaint.Response respo = respon.getResponse();

            String result = respo.getResult();
            String data = respo.getData();
            if (result.equalsIgnoreCase("Success")) {

                Toast.makeText(getApplicationContext(), data, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Activity_Post_Complaint.this, MainActivity.class);
                startActivity(intent);

            } else {

                Toast.makeText(getApplicationContext(), data, Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onFailure(Call<PostComplaint> call, Throwable t) {
            progressDoalog.dismiss();
            Log.d("Error", "" + t.getMessage());
            call.cancel();
        }


    });

API Interface

@Multipart
@POST("/somelink.php?")
Call<PostComplaint> postComplaint(@Part MultipartBody.Part file,
                               @Part("photo") RequestBody name,
                               @PartMap Map<String, RequestBody> fields);

APIClient.java

public class APIClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor)
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();

        retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.1.135")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();

        return retrofit;
    }

}
like image 243
sangavi Avatar asked Apr 14 '17 09:04

sangavi


4 Answers

Try

int compressionRatio = 2; //1 == originalImage, 2 = 50% compression, 4=25% compress
File file = new File (imageUrl);
try {
    Bitmap bitmap = BitmapFactory.decodeFile (file.getPath ());
    bitmap.compress (Bitmap.CompressFormat.JPEG, compressionRatio, new FileOutputStream (file));
}
catch (Throwable t) {
    Log.e("ERROR", "Error compressing file." + t.toString ());
    t.printStackTrace ();
}
like image 78
PEHLAJ Avatar answered Oct 23 '22 03:10

PEHLAJ


If you are looking for image compression, you may use this library https://github.com/zetbaitsu/Compressor . It is pretty much simple and awesome. The link explains it all.

like image 27
Anudeep Avatar answered Oct 23 '22 01:10

Anudeep


you can using from ImageZipper for image compression, you can change its size and quality

Add this to your root build.gradle file:

allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

Add this to your app module's build.gradle file:

implementation 'com.github.amanjeetsingh150:ImageZipper:1.3'

Custom Compressor :

 File imageZipperFile=new ImageZipper(MainActivity.this)
                    .setQuality(50)
                    .setMaxWidth(300)
                    .setMaxHeight(300)
                    .compressToFile(actualFile);

   RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), imageZipperFile);
                MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", URLEncoder.encode(imageZipperFile.getName(), "utf-8"), requestBody);
                RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), Hawk.get("auth_email").toString());
                Call<ResponseModel> call = service.fileUpload(filename,fileToUpload);

OK Now Get Bitmap!!

 Bitmap b=new ImageZipper(MainActivity.this).compressToBitmap(actualFile);
like image 32
hosein moradi Avatar answered Oct 23 '22 03:10

hosein moradi


try following code:

Bitmap bmp = BitmapFactory.decodeFile(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", "filename");
like image 2
Firoz Jaroli Avatar answered Oct 23 '22 02:10

Firoz Jaroli