如何压缩Feed中的图片

时间:2018-03-15 04:08:20

标签: java android

我创建了一个像twitter github

这样的简单应用

我计划压缩图片以避免使用Android。我使用Bitmapfactory.decodeFile来做,因为你知道我需要计算inSampleSize。但是我在getWidth()getHeight()后得到0,那么我如何才能在ImageView recyclerview中获得adapter的大小?

3 个答案:

答案 0 :(得分:0)

A
     

在RecyclerView onBindViewHolder方法中使用波纹管代码

 // glide
    compile 'com.github.bumptech.glide:glide:3.7.0'

答案 1 :(得分:0)

Bitmap original = BitmapFactory.decodeStream(getAssets().open("1024x768.jpg"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
original.compress(Bitmap.CompressFormat.PNG, 100, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

Log.e("Original   dimensions", original.getWidth()+" "+original.getHeight());
Log.e("Compressed dimensions", decoded.getWidth()+" "+decoded.getHeight());

也许您从资源中获取位图,在这种情况下,位图尺寸将取决于手机屏幕密度

Bitmap bitmap=((BitmapDrawable)getResources().getDrawable(R.drawable.img_1024x768)).getBitmap();
    Log.e("Dimensions", bitmap.getWidth()+" "+bitmap.getHeight());

答案 2 :(得分:0)

创建后,您不会立即获得imageView的大小。因此,您必须使用可运行的实现调用该视图的post方法,以便在加载图像后执行代码。

    imageView.post(new Runnable() {
        @Override
        public void run() {
            // Your code to load image here
            // Here you wil get the actual width and height of imageView for sure
            // Try to use getMeasuredWidth() and getMeasuredWidth() if needed
        }
    });

您可以根据要将图像应用到的视图大小来计算采样。

我用自定义图像加载器创建了一个项目。这是我编写的用于采样和加载图像的位图辅助类。

  

(仅当图像在存储或资源中时才有效)

<强> BitmapLoader https://github.com/sujithkanna/MenuCardAnimation/blob/master/app/src/main/java/com/hsalf/menuanim/utils/BitmapHelper.java