热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

Android图片压缩(质量压缩和尺寸压缩)

在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可

在网上调查了图片压缩的方法并实装后,大致上可以认为有两类压缩:质量压缩(不改变图片的尺寸)和尺寸压缩(相当于是像素上的压缩);质量压缩一般可用于上传大图前的处理,这样就可以节省一定的流量,毕竟现在的手机拍照都能达到3M左右了,尺寸压缩一般可用于生成缩略图。

两种方法都实装在了我的项目中,结果却发现在质量压缩的模块中,本来1.9M的图片压缩后反而变成3M多了,很是奇怪,再做了进一步调查终于知道原因了。下面这个博客说的比较清晰:

android图片压缩总结

总 结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap,所谓的质量压缩,它其实只能实现对 file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但 是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小 了;

而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;

最后把自己总结的工具类贴出来:

import javaioByteArrayInputStream; 
import javaioByteArrayOutputStream; 
import javaioFile; 
import javaioFileNotFoundException; 
import javaioFileOutputStream; 
import javaioIOException; 
 
import androidgraphicsBitmap; 
import androidgraphicsBitmapConfig; 
import androidgraphicsBitmapFactory; 
 
/** 
 * Image compress factory class 
 * 
 * @author 
 * 
 */ 
public class ImageFactory { 
 
  /** 
   * Get bitmap from specified image path 
   * 
   * @param imgPath 
   * @return 
   */ 
  public Bitmap getBitmap(String imgPath) { 
    // Get bitmap through image path 
    BitmapFactoryOptions newOpts = new BitmapFactoryOptions(); 
    newOptsinJustDecodeBounds = false; 
    newOptsinPurgeable = true; 
    newOptsinInputShareable = true; 
    // Do not compress 
    newOptsinSampleSize = 1; 
    newOptsinPreferredCOnfig= ConfigRGB_565; 
    return BitmapFactorydecodeFile(imgPath, newOpts); 
  } 
   
  /** 
   * Store bitmap into specified image path 
   * 
   * @param bitmap 
   * @param outPath 
   * @throws FileNotFoundException 
   */ 
  public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException { 
    FileOutputStream os = new FileOutputStream(outPath); 
    bitmapcompress(BitmapCompressFormatJPEG, 100, os); 
  } 
   
  /** 
   * Compress image by pixel, this will modify image width/height 
   * Used to get thumbnail 
   * 
   * @param imgPath image path 
   * @param pixelW target pixel of width 
   * @param pixelH target pixel of height 
   * @return 
   */ 
  public Bitmap ratio(String imgPath, float pixelW, float pixelH) { 
    BitmapFactoryOptions newOpts = new BitmapFactoryOptions();  
    // 开始读入图片,此时把optionsinJustDecodeBounds 设回true,即只读边不读内容 
    newOptsinJustDecodeBounds = true; 
    newOptsinPreferredCOnfig= ConfigRGB_565; 
    // Get bitmap info, but notice that bitmap is null now  
    Bitmap bitmap = BitmapFactorydecodeFile(imgPath,newOpts); 
      
    newOptsinJustDecodeBounds = false;  
    int w = newOptsoutWidth;  
    int h = newOptsoutHeight;  
    // 想要缩放的目标尺寸 
    float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了 
    float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了 
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
    int be = 1;//be=1表示不缩放  
    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
      be = (int) (newOptsoutWidth / ww);  
    } else if (w  hh) {//如果高度高的话根据宽度固定大小缩放  
      be = (int) (newOptsoutHeight / hh);  
    }  
    if (be <= 0) be = 1;  
    newOptsinSampleSize = be;//设置缩放比例 
    // 开始压缩图片,注意此时已经把optionsinJustDecodeBounds 设回false了 
    bitmap = BitmapFactorydecodeFile(imgPath, newOpts); 
    // 压缩好比例大小后再进行质量压缩 
//    return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 
    return bitmap; 
  } 
   
  /** 
   * Compress image by size, this will modify image width/height 
   * Used to get thumbnail 
   * 
   * @param image 
   * @param pixelW target pixel of width 
   * @param pixelH target pixel of height 
   * @return 
   */ 
  public Bitmap ratio(Bitmap image, float pixelW, float pixelH) { 
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    imagecompress(BitmapCompressFormatJPEG, 100, os); 
    if( ostoByteArray()length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactorydecodeStream)时溢出   
      osreset();//重置baos即清空baos  
      imagecompress(BitmapCompressFormatJPEG, 50, os);//这里压缩50%,把压缩后的数据存放到baos中  
    }  
    ByteArrayInputStream is = new ByteArrayInputStream(ostoByteArray());  
    BitmapFactoryOptions newOpts = new BitmapFactoryOptions();  
    //开始读入图片,此时把optionsinJustDecodeBounds 设回true了  
    newOptsinJustDecodeBounds = true; 
    newOptsinPreferredCOnfig= ConfigRGB_565; 
    Bitmap bitmap = BitmapFactorydecodeStream(is, null, newOpts);  
    newOptsinJustDecodeBounds = false;  
    int w = newOptsoutWidth;  
    int h = newOptsoutHeight;  
    float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了 
    float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了 
    //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可  
    int be = 1;//be=1表示不缩放  
    if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放  
      be = (int) (newOptsoutWidth / ww);  
    } else if (w  hh) {//如果高度高的话根据宽度固定大小缩放  
      be = (int) (newOptsoutHeight / hh);  
    }  
    if (be <= 0) be = 1;  
    newOptsinSampleSize = be;//设置缩放比例  
    //重新读入图片,注意此时已经把optionsinJustDecodeBounds 设回false了  
    is = new ByteArrayInputStream(ostoByteArray());  
    bitmap = BitmapFactorydecodeStream(is, null, newOpts); 
    //压缩好比例大小后再进行质量压缩 
//   return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 
    return bitmap; 
  } 
   
  /** 
   * Compress by quality, and generate image to the path specified 
   * 
   * @param image 
   * @param outPath 
   * @param maxSize target will be compressed to be smaller than this size(kb) 
   * @throws IOException 
   */ 
  public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException { 
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    // scale 
    int optiOns= 100; 
    // Store the bitmap into output stream(no compress) 
    imagecompress(BitmapCompressFormatJPEG, options, os);  
    // Compress by loop 
    while ( ostoByteArray()length / 1024 > maxSize) { 
      // Clean up os 
      osreset(); 
      // interval 10 
      options -= 10; 
      imagecompress(BitmapCompressFormatJPEG, options, os); 
    } 
     
    // Generate compressed image file 
    FileOutputStream fos = new FileOutputStream(outPath);  
    foswrite(ostoByteArray());  
    fosflush();  
    fosclose();  
  } 
   
  /** 
   * Compress by quality, and generate image to the path specified 
   * 
   * @param imgPath 
   * @param outPath 
   * @param maxSize target will be compressed to be smaller than this size(kb) 
   * @param needsDelete Whether delete original file after compress 
   * @throws IOException 
   */ 
  public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) throws IOException { 
    compressAndGenImage(getBitmap(imgPath), outPath, maxSize); 
     
    // Delete original file 
    if (needsDelete) { 
      File file = new File (imgPath); 
      if (fileexists()) { 
        filedelete(); 
      } 
    } 
  } 
   
  /** 
   * Ratio and generate thumb to the path specified 
   * 
   * @param image 
   * @param outPath 
   * @param pixelW target pixel of width 
   * @param pixelH target pixel of height 
   * @throws FileNotFoundException 
   */ 
  public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) throws FileNotFoundException { 
    Bitmap bitmap = ratio(image, pixelW, pixelH); 
    storeImage( bitmap, outPath); 
  } 
   
  /** 
   * Ratio and generate thumb to the path specified 
   * 
   * @param image 
   * @param outPath 
   * @param pixelW target pixel of width 
   * @param pixelH target pixel of height 
   * @param needsDelete Whether delete original file after compress 
   * @throws FileNotFoundException 
   */ 
  public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) throws FileNotFoundException { 
    Bitmap bitmap = ratio(imgPath, pixelW, pixelH); 
    storeImage( bitmap, outPath); 
     
    // Delete original file 
        if (needsDelete) { 
          File file = new File (imgPath); 
          if (fileexists()) { 
            filedelete(); 
          } 
        } 
  } 
   
} 

android图片压缩总结

一.图片的存在形式

1.文件形式(即以二进制形式存在于硬盘上)

2.流的形式(即以二进制形式存在于内存中)

3.Bitmap形式

这三种形式的区别: 文件形式和流的形式对图片体积大小并没有影响,也就是说,如果你手机SD卡上的如果是100K,那 么通过流的形式读到内存中,也一定是占100K的内存,注意是流的形式,不是Bitmap的形式,当图片以Bitmap的形式存在时,其占用的内存会瞬间 变大, 我试过500K文件形式的图片加载到内存,以Bitmap形式存在时,占用内存将近10M,当然这个增大的倍数并不是固定的

检测图片三种形式大小的方法:

文件形式: file.length()

流的形式: 讲图片文件读到内存输入流中,看它的byte数

Bitmap: bitmap.getByteCount()

二.常见的压缩方式

1. 将图片保存到本地时进行压缩, 即将图片从Bitmap形式变为File形式时进行压缩,

特点是:  File形式的图片确实被压缩了, 但是当你重新读取压缩后的file为 Bitmap是,它占用的内存并没有改变  

方法说明: 该方法是压缩图片的质量, 注意它不会减少图片的像素,比方说, 你的图片是300K的, 1280*700像素的, 经过该方法压缩后, File形式的图片是在100以下, 以方便上传服务器, 但是你BitmapFactory.decodeFile到内存中,变成Bitmap时,它的像素仍然是1280*700, 计算图片像素的方法是 bitmap.getWidth()和bitmap.getHeight(), 图片是由像素组成的, 每个像素又包含什么呢&#63; 熟悉PS的人知道, 图片是有色相,明度和饱和度构成的.

public static void compressBmpToFile(Bitmap bmp,File file){ 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    int optiOns= 80;//个人喜欢从80开始, 
    bmp.compress(Bitmap.CompressFormat.JPEG, options, baos); 
    while (baos.toByteArray().length / 1024 > 100) {  
      baos.reset(); 
      options -= 10; 
      bmp.compress(Bitmap.CompressFormat.JPEG, options, baos); 
    } 
    try { 
      FileOutputStream fos = new FileOutputStream(file); 
      fos.write(baos.toByteArray()); 
      fos.flush(); 
      fos.close(); 
    } catch (Exception e) { 
      e.printStackTrace(); 
    } 
  } 

该方法的官方文档也解释说, 它会让图片重新构造, 但是有可能图像的位深(即色深)和每个像素的透明度会变化,JPEG onlysupports opaque(不透明), 也就是说以jpeg格式压缩后, 原来图片中透明的元素将消失.所以这种格式很可能造成失真

既然它是改变了图片的显示质量, 达到了对File形式的图片进行压缩, 图片的像素没有改变的话, 那重新读取经过压缩的file为Bitmap时, 它占用的内存并不会少.(不相信的可以试试)

因为: bitmap.getByteCount() 是计算它的像素所占用的内存, 请看官方解释: Returns the number of bytes used to store this bitmap's pixels.

2.   将图片从本地读到内存时,进行压缩 ,即图片从File形式变为Bitmap形式

特点: 通过设置采样率, 减少图片的像素, 达到对内存中的Bitmap进行压缩

先看一个方法: 该方法是对内存中的Bitmap进行质量上的压缩, 由上面的理论可以得出该方法是无效的, 而且也是没有必要的,因为你已经将它读到内存中了,再压缩多此一举, 尽管在获取系统相册图片时,某些手机会直接返回一个Bitmap,但是这种情况下, 返回的Bitmap都是经过压缩的, 它不可能直接返回一个原声的Bitmap形式的图片, 后果可想而知

方法说明: 该方法就是对Bitmap形式的图片进行压缩, 也就是通过设置采样率, 减少Bitmap的像素, 从而减少了它所占用的内存

private Bitmap compressBmpFromBmp(Bitmap image) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    int optiOns= 100; 
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    while (baos.toByteArray().length / 1024 > 100) {  
      baos.reset(); 
      options -= 10; 
      image.compress(Bitmap.CompressFormat.JPEG, options, baos); 
    } 
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); 
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null); 
    return bitmap; 
  } 

再看一个方法:

  private Bitmap compressImageFromFile(String srcPath) { 
    BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
    newOpts.inJustDecodeBounds = true;//只读边,不读内容 
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); 
 
    newOpts.inJustDecodeBounds = false; 
    int w = newOpts.outWidth; 
    int h = newOpts.outHeight; 
    float hh = 800f;// 
    float ww = 480f;// 
    int be = 1; 
    if (w > h && w > ww) { 
      be = (int) (newOpts.outWidth / ww); 
    } else if (w  hh) { 
      be = (int) (newOpts.outHeight / hh); 
    } 
    if (be <= 0) 
      be = 1; 
    newOpts.inSampleSize = be;//设置采样率 
     
    newOpts.inPreferredCOnfig= Config.ARGB_8888;//该模式是默认的,可不设 
    newOpts.inPurgeable = true;// 同时设置才会有效 
    newOpts.inInputShareable = true;//。当系统内存不够时候图片自动被回收 
     
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts); 
//   return compressBmpFromBmp(bitmap);//原来的方法调用了这个方法企图进行二次压缩 
                  //其实是无效的,大家尽管尝试 
    return bitmap; 
  } 

分享个按照图片尺寸压缩:

public static void compressPicture(String srcPath, String desPath) { 
    FileOutputStream fos = null; 
    BitmapFactoryOptions op = new BitmapFactoryOptions(); 
 
    // 开始读入图片,此时把optionsinJustDecodeBounds 设回true了 
    opinJustDecodeBounds = true; 
    Bitmap bitmap = BitmapFactorydecodeFile(srcPath, op); 
    opinJustDecodeBounds = false; 
 
    // 缩放图片的尺寸 
    float w = opoutWidth; 
    float h = opoutHeight; 
    float hh = 1024f;// 
    float ww = 1024f;// 
    // 最长宽度或高度1024 
    float be = 0f; 
    if (w > h && w > ww) { 
      be = (float) (w / ww); 
    } else if (w  hh) { 
      be = (float) (h / hh); 
    } 
    if (be <= 0) { 
      be = 0f; 
    } 
    opinSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小 
    // 重新读入图片,注意此时已经把optionsinJustDecodeBounds 设回false了 
    bitmap = BitmapFactorydecodeFile(srcPath, op); 
    int desWidth = (int) (w / be); 
    int desHeight = (int) (h / be); 
    bitmap = BitmapcreateScaledBitmap(bitmap, desWidth, desHeight, true); 
    try { 
      fos = new FileOutputStream(desPath); 
      if (bitmap != null) { 
        bitmapcompress(BitmapCompressFormatJPEG, 100, fos); 
      } 
    } catch (FileNotFoundException e) { 
      eprintStackTrace(); 
    } 
  } 

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


推荐阅读
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 本文介绍了使用AJAX的POST请求实现数据修改功能的方法。通过ajax-post技术,可以实现在输入某个id后,通过ajax技术调用post.jsp修改具有该id记录的姓名的值。文章还提到了AJAX的概念和作用,以及使用async参数和open()方法的注意事项。同时强调了不推荐使用async=false的情况,并解释了JavaScript等待服务器响应的机制。 ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • PHP设置MySQL字符集的方法及使用mysqli_set_charset函数
    本文介绍了PHP设置MySQL字符集的方法,详细介绍了使用mysqli_set_charset函数来规定与数据库服务器进行数据传送时要使用的字符集。通过示例代码演示了如何设置默认客户端字符集。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • 本文介绍了在Hibernate配置lazy=false时无法加载数据的问题,通过采用OpenSessionInView模式和修改数据库服务器版本解决了该问题。详细描述了问题的出现和解决过程,包括运行环境和数据库的配置信息。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 本文介绍了如何找到并终止在8080端口上运行的进程的方法,通过使用终端命令lsof -i :8080可以获取在该端口上运行的所有进程的输出,并使用kill命令终止指定进程的运行。 ... [详细]
  • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
    VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
  • 本文详细介绍了云服务器API接口的概念和作用,以及如何使用API接口管理云上资源和开发应用程序。通过创建实例API、调整实例配置API、关闭实例API和退还实例API等功能,可以实现云服务器的创建、配置修改和销毁等操作。对于想要学习云服务器API接口的人来说,本文提供了详细的入门指南和使用方法。如果想进一步了解相关知识或阅读更多相关文章,请关注编程笔记行业资讯频道。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
author-avatar
hz--Ives
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有