全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

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大小对比

 

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


# Android  # 图片压缩  # android图片压缩算法  # android图片压缩的3种方法实例  # Android拍照得到全尺寸图片并进行压缩  # android 将图片压缩到指定的大小的示例  # Android WebP 图片压缩与传输  # Android实现简单图片压缩的方法  # Android图片压缩以及优化实例  # Android图片压缩(质量压缩和尺寸压缩)  # Android图片实现压缩处理的实例代码  # 加载  # 设置为  # 就可以  # 自己的  # 采样率  # 以此类推  # 用了  # 这个时候  # 先把  # 会去  # 来实现  # 大家多多  # 来写  # 主要是  # 也就是说  # 完成了  # 是一样的  # decodeResource  # decodeSampledBitmapFromDescrptor  # halfWidth 


相关文章: 如何在Ubuntu系统下快速搭建WordPress个人网站?  ,在苏州找工作,上哪个网站比较好?  如何通过智能用户系统一键生成高效建站方案?  网站视频怎么制作,哪个网站可以免费收看好莱坞经典大片?  如何在阿里云购买域名并搭建网站?  建站之星体验版:智能建站系统+响应式设计,多端适配快速建站  成都网站制作价格表,现在成都广电的单独网络宽带有多少的,资费是什么情况呢?  建站之星如何助力企业快速打造五合一网站?  如何通过主机屋免费建站教程十分钟搭建网站?  Android自定义listview布局实现上拉加载下拉刷新功能  高端智能建站公司优选:品牌定制与SEO优化一站式服务  如何通过NAT技术实现内网高效建站?  Dapper的Execute方法的返回值是什么意思 Dapper Execute返回值详解  网站插件制作软件免费下载,网页视频怎么下到本地插件?  javascript中的try catch异常捕获机制用法分析  如何快速启动建站代理加盟业务?  制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?  湖南网站制作公司,湖南上善若水科技有限公司做什么的?  微信h5制作网站有哪些,免费微信H5页面制作工具?  如何选择适配移动端的WAP自助建站平台?  如何在阿里云虚拟服务器快速搭建网站?  ,南京靠谱的征婚网站?  建站ABC备案流程中有哪些关键注意事项?  制作充值网站的软件,做人力招聘为什么要自己交端口钱?  rsync同步时出现rsync: failed to set times on “xxxx”: Operation not permitted  建站VPS推荐:2025年高性能服务器配置指南  香港服务器租用每月最低只需15元?  家具网站制作软件,家具厂怎么跑业务?  网站微信制作软件,如何制作微信链接?  建站之星CMS建站配置指南:模板选择与SEO优化技巧  如何在IIS服务器上快速部署高效网站?  大型企业网站制作流程,做网站需要注册公司吗?  php能控制zigbee模块吗_php通过串口与cc2530 zigbee通信【介绍】  制作假网页,招聘网的薪资待遇,会有靠谱的吗?一面试又各种折扣?  无锡营销型网站制作公司,无锡网选车牌流程?  建站主机系统SEO优化与智能配置核心关键词操作指南  岳西云建站教程与模板下载_一站式快速建站系统操作指南  如何在阿里云ECS服务器部署织梦CMS网站?  公司网站的制作公司,企业网站制作基本流程有哪些?  如何在阿里云完成域名注册与建站?  建站org新手必看:2024最新搭建流程与模板选择技巧  宝华建站服务条款解析:五站合一功能与SEO优化设置指南  零服务器AI建站解决方案:快速部署与云端平台低成本实践  如何制作新型网站程序文件,新型止水鱼鳞网要拆除吗?  如何快速选择适合个人网站的云服务器配置?  视频网站制作教程,怎么样制作优酷网的小视频?  如何在景安服务器上快速搭建个人网站?  深圳网站制作案例,网页的相关名词有哪些?  MySQL查询结果复制到新表的方法(更新、插入)  建站之星×万网:智能建站系统+自助建站平台一键生成 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。