如何使用适用于Android的Picasso库压缩图像? [英] How to compress image using Picasso Library for Android?

查看:218
本文介绍了如何使用适用于Android的Picasso库压缩图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序使用Camera Intent捕获图像.图像将另存为"abc.jpg"文件.现在使用Picasso Library,我尝试通过调整大小来压缩图像.我没有任何输出.我的代码从未到达目标的onBitmapLoaded,也从未到达onBitmapFailed.这是我的代码.

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) {
                    }
                });

}
}
}

推荐答案

您不应将Target用作匿名类.为它定义一个对象,然后将此引用传递给into()函数.例如:

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(){...}

然后

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.

告诉我它是否有效.

这篇关于如何使用适用于Android的Picasso库压缩图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆