Android实现图片压缩示例代码

 更新时间:2017年01月18日 14:33:23   作者:柠萌草的味道  
本篇文章主要介绍了Android实现图片压缩示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

核心思想是通过BitmapFactory.Options来缩放图片,主要是用到了它的inSampleSize参数(采样率)

当inSampleSize为1的时候,采样后的图片大小为图片的原始大小;

当inSampleSize为2的时候,采样后的图片的宽和高是原来的1/2,也就是说,它的像素点是原来的1/4,占的内存自然就是原来的1/4了。以此类推。

当inSampleSize小于1的时候,效果和等于1的时候是一样的。

压缩流程如下:

1.BitmapFactory.Options 的inJustDecodeBounds参数设置为true(这个时候BitmapFactory只是解析图片的原始宽高,并不会去加载图片)。

2.从BitmapFactory.Options 中取出图片的原始宽高,outWidth,outHeight。

3.根据自己的需要设置合适的采样率。

4.BitmapFactory.Options 的inJustDecodeBounds参数设置为false,然后就可以加载图片了。

下面我们看代码:

public Bitmap decodeSampledBitmapFromBytes(byte[] bytes,int reqWidth,int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
  }


public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
    if(reqWidth == 0 || reqHeight == 0){
      return 1;
    }
    final int width = options.outWidth;
    final int height = options.outHeight;
    int inSampleSize = 1;
    if( width > reqWidth || height > reqHeight){
      final int halfWidth = width / 2;
      final int halfHeight = height / 2;
      while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight){
        inSampleSize *=2;
      }
    }
    return inSampleSize;
  }

如此一来,就完成了一张图片的压缩。另外,BitmapFactory还有其它的decode方法,我们也可以仿照上面的来写。

public Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res,resId,options);
    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res,resId,options);
  }
public Bitmap decodeSampledBitmapFromDescrptor(FileDescriptor fd,int reqWidth,int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fd,null,options);
    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFileDescriptor(fd,null,options);
  }

接下来结合一个小demo来实现一个完整的流程

先把图片压缩类封装起来

public class ImageResizer {
  private static final String TAG = "ImageResizer";

  public ImageResizer(){}

  public Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res,resId,options);
    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res,resId,options);
  }

  public Bitmap decodeSampledBitmapFromBytes(byte[] bytes,int reqWidth,int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap a = BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
    Log.d(TAG, "before bitmap : " + a.getRowBytes() * a.getHeight());
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
    options.inJustDecodeBounds = false;
    Bitmap b = BitmapFactory.decodeByteArray(bytes,0,bytes.length,options);
    Log.d(TAG, "after bitmap : " + b.getRowBytes() * b.getHeight());
    return b;
  }

  public Bitmap decodeSampledBitmapFromDescrptor(FileDescriptor fd,int reqWidth,int reqHeight){
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFileDescriptor(fd,null,options);
    options.inSampleSize = calculateInSampleSize(options,reqWidth,reqHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeFileDescriptor(fd,null,options);
  }

  public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight){
    if(reqWidth == 0 || reqHeight == 0){
      return 1;
    }
    final int width = options.outWidth;
    final int height = options.outHeight;
    int inSampleSize = 1;
    if( width > reqWidth || height > reqHeight){
      final int halfWidth = width / 2;
      final int halfHeight = height / 2;
      while ((halfWidth / inSampleSize) >= reqWidth && (halfHeight / inSampleSize) >= reqHeight){
        inSampleSize *=2;
      }
    }
    return inSampleSize;
  }
}

然后就可以拿来用了:

activity_main2.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/activity_main2"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context="com.example.yuan.test.Main2Activity">

  <ImageView
    android:id="@+id/main2Iv"
    android:layout_width="200dp"
    android:layout_height="200dp" />

</RelativeLayout>

Main2Activity.Java

public class Main2Activity extends AppCompatActivity {

  private ImageView iv;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    initView();
    testHttp(iv);
  }

  private void testHttp(final ImageView iv) {

    new Thread(new Runnable() {
      @Override
      public void run() {
        String urlString = "https://static.pexels.com/photos/295818/pexels-photo-295818.jpeg";
        HttpURLConnection urlConnection = null;
        InputStream in = null;
        ByteArrayOutputStream outStream = null;
        try {
          URL url = new URL(urlString);
          urlConnection = (HttpURLConnection) url.openConnection();
          in = urlConnection.getInputStream();
          byte[] buffer = new byte[1024];
          int len;
          outStream = new ByteArrayOutputStream();
          while ((len = in.read(buffer)) != -1){
            outStream.write(buffer,0,len);
          }
          final byte[] data = outStream.toByteArray();
          runOnUiThread(new Runnable() {
            @Override
            public void run() { //在主线程加载UI
              iv.setImageBitmap(new ImageResizer().decodeSampledBitmapFromBytes(data,200,200));
            }
          });
        } catch (IOException e) {
          e.printStackTrace();
        }finally {
          try {
            if(urlConnection !=null){
              urlConnection.disconnect();
            }
            if(in != null){
              in.close();
            }
            if(outStream != null){
              outStream.close();
            }
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    }).start();
  }

  private void initView() {
    iv = (ImageView) findViewById(R.id.main2Iv);
  }
}

最后记得获取网络权限

运行的结果:

压缩前后的bitmap大小对比

压缩前后的bitmap大小对比

压缩前后的bitmap大小对比

这里写图片描述 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析

    Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析

    本文主要介绍 Android系统进程间通信Binder机制Java 接口源码分析,这里详细介绍了如何实现Binder 机制和Java接口直接的通信,有兴趣的小伙伴可以参考下
    2016-08-08
  • Flutter状态管理Bloc之定时器示例

    Flutter状态管理Bloc之定时器示例

    这篇文章主要为大家详细介绍了Flutter状态管理Bloc之定时器示例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-03-03
  • Android BottomNavigationView与Fragment重建与重叠问题解决方法探索

    Android BottomNavigationView与Fragment重建与重叠问题解决方法探索

    这篇文章主要介绍了Android BottomNavigationView与Fragment重建与重叠问题解决,总的来说这并不是一道难题,那为什么要拿出这道题介绍?拿出这道题真正想要传达的是解题的思路,以及不断优化探寻最优解的过程。希望通过这道题能给你带来一种解题优化的思路
    2023-01-01
  • Android中删除Preference详解

    Android中删除Preference详解

    这篇文章主要介绍了Android中删除Preference详解,很多时候删除Preference总会失败,本文着重分析删除失败的原因,需要的朋友可以参考下
    2015-01-01
  • Android实现打地鼠小游戏

    Android实现打地鼠小游戏

    这篇文章主要为大家详细介绍了Android实现打地鼠小游戏,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • Android基于OpenCV实现Harris角点检测

    Android基于OpenCV实现Harris角点检测

    角点就是极值点,即在某方面属性特别突出的点。当然,你可以自己定义角点的属性(设置特定熵值进行角点检测)。角点可以是两条线的交叉处,也可以是位于相邻的两个主要方向不同的事物上的点。本文介绍如何基于OpenCV实现Harris角点检测
    2021-06-06
  • Android仿头条、微信大图预览视图的方法详解

    Android仿头条、微信大图预览视图的方法详解

    大图预览应该对大家来说都不陌生,下面这篇文章主要给大家介绍了关于Android仿头条、微信大图预览视图的相关资料,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧。
    2018-03-03
  • Android 分析实现性能优化之启动速度优化

    Android 分析实现性能优化之启动速度优化

    在移动端程序中,用户希望的是应用能够快速打开。启动时间过长的应用不能满足这个期望,并且可能会令用户失望。轻则鄙视你,重则直接卸载你的应用
    2021-11-11
  • Android Studio 中aidl的自定义类的使用详解

    Android Studio 中aidl的自定义类的使用详解

    这篇文章主要介绍了Android Studio 中aidl的自定义类的使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • Android 实现微信,微博,微信朋友圈,QQ分享的功能

    Android 实现微信,微博,微信朋友圈,QQ分享的功能

    这篇文章主要介绍了Android 实现微信,微博,微信朋友圈,QQ分享的功能的相关资料,需要的朋友可以参考下
    2016-12-12

最新评论