How to compress image using Picasso Library for Android?

孤者浪人 提交于 2019-12-11 13:48:40

问题


My Application captures Image using Camera Intent. The image is saved to a file as "abc.jpg". Now using Picasso Library I try to compress the image by resizing it. I dont get any output. My code never reaches the Target's onBitmapLoaded neither onBitmapFailed. Here is my code.

public static final String DATA_PATH = Environment
.getExternalStorageDirectory() + "/SnapReminder/";
File file1 = new File(DATA_PATH);
file1.mkdirs();
String _path = DATA_PATH + "abc.jpg";
File file = new File(_path);
Uri imageUri = Uri.fromFile(file);
final Intent intent = new
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
startActivityForResult(intent, 0);



protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0) {
  if (resultCode == RESULT_OK) {
  Picasso.with(context)
  .load(_path)
  .resize(size, size)
  .centerCrop()
  .into(new Target() {
       @Override
       public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom
       from) {              
                        File file = new File(_path);
                        try {
                            file.createNewFile();
                            FileOutputStream ostream = new FileOutputStream(file);
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                            ostream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {
                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {
                    }
                });

}
}
}

回答1:


You shouldn't use Target as an anonym class. Define an object for it and pass this reference to the into() function. For example:

Target myTarget = new Target(){...}

and then,

Picasso.with(context) .load(_path).resize(size, size).centerCrop().into(myTarget);  

The reason for this is that an anonym class gives a really weak reference, which means that the Target gets Garbage collected.

Tell me if it worked.



来源:https://stackoverflow.com/questions/37457899/how-to-compress-image-using-picasso-library-for-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!