Android图片压缩(质量压缩和尺寸压缩)Bitmap转成字符串上传
两种方法都实装在了我的项目中,结果却发现在质量压缩的模块中,本来1.9M的图片压缩后反而变成3M多了,很是奇怪,再做了进一步调查终于知道原因了。下面这个博客说的比较清晰:
android图片压缩总结
总结来看,图片有三种存在形式:硬盘上时是file,网络传输时是stream,内存中是stream或bitmap,所谓的质量压缩,它其实只能实现对file的影响,你可以把一个file转成bitmap再转成file,或者直接将一个bitmap转成file时,这个最终的file是被压缩过的,但是中间的bitmap并没有被压缩(或者说几乎没有被压缩,我不确定),因为bigmap在内存中的大小是按像素计算的,也就是width * height,对于质量压缩,并不会改变图片的像素,所以就算质量被压缩了,但是bitmap在内存的占有率还是没变小,但你做成file时,它确实变小了;
而尺寸压缩由于是减小了图片的像素,所以它直接对bitmap产生了影响,当然最终的file也是相对的变小了;
最后把自己总结的工具类贴出来:
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import android.graphics.Bitmap;
- import android.graphics.Bitmap.Config;
- import android.graphics.BitmapFactory;
- /**
- * 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
- BitmapFactory.Options newOpts = new BitmapFactory.Options();
- newOpts.inJustDecodeBounds = false;
- newOpts.inPurgeable = true;
- newOpts.inInputShareable = true;
- // Do not compress
- newOpts.inSampleSize = 1;
- newOpts.inPreferredConfig = Config.RGB_565;
- return BitmapFactory.decodeFile(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);
- bitmap.compress(Bitmap.CompressFormat.JPEG, 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) {
- BitmapFactory.Options newOpts = new BitmapFactory.Options();
- // 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容
- newOpts.inJustDecodeBounds = true;
- newOpts.inPreferredConfig = Config.RGB_565;
- // Get bitmap info, but notice that bitmap is null now
- Bitmap bitmap = BitmapFactory.decodeFile(imgPath,newOpts);
- newOpts.inJustDecodeBounds = false;
- int w = newOpts.outWidth;
- int h = newOpts.outHeight;
- // 想要缩放的目标尺寸
- float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
- float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
- // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
- int be = 1;//be=1表示不缩放
- if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
- be = (int) (newOpts.outWidth / ww);
- } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
- be = (int) (newOpts.outHeight / hh);
- }
- if (be <= 0) be = 1;
- newOpts.inSampleSize = be;//设置缩放比例
- // 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了
- bitmap = BitmapFactory.decodeFile(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();
- image.compress(Bitmap.CompressFormat.JPEG, 100, os);
- if( os.toByteArray().length / 1024>1024) {//判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出
- os.reset();//重置baos即清空baos
- image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%,把压缩后的数据存放到baos中
- }
- ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
- BitmapFactory.Options newOpts = new BitmapFactory.Options();
- //开始读入图片,此时把options.inJustDecodeBounds 设回true了
- newOpts.inJustDecodeBounds = true;
- newOpts.inPreferredConfig = Config.RGB_565;
- Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
- newOpts.inJustDecodeBounds = false;
- int w = newOpts.outWidth;
- int h = newOpts.outHeight;
- float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了
- float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了
- //缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可
- int be = 1;//be=1表示不缩放
- if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
- be = (int) (newOpts.outWidth / ww);
- } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
- be = (int) (newOpts.outHeight / hh);
- }
- if (be <= 0) be = 1;
- newOpts.inSampleSize = be;//设置缩放比例
- //重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
- is = new ByteArrayInputStream(os.toByteArray());
- bitmap = BitmapFactory.decodeStream(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)
- image.compress(Bitmap.CompressFormat.JPEG, options, os);
- // Compress by loop
- while ( os.toByteArray().length / 1024 > maxSize) {
- // Clean up os
- os.reset();
- // interval 10
- options -= 10;
- image.compress(Bitmap.CompressFormat.JPEG, options, os);
- }
- // Generate compressed image file
- FileOutputStream fos = new FileOutputStream(outPath);
- fos.write(os.toByteArray());
- fos.flush();
- fos.close();
- }
- /**
- * 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 (file.exists()) {
- file.delete();
- }
- }
- }
- /**
- * 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 (file.exists()) {
- file.delete();
- }
- }
- }
- }
android图片压缩总结
一.图片的存在形式
2.流的形式(即以二进制形式存在于内存中)
3.Bitmap形式
二.常见的压缩方式
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(); } }
既然它是改变了图片的显示质量, 达到了对File形式的图片进行压缩, 图片的像素没有改变的话, 那重新读取经过压缩的file为Bitmap时, 它占用的内存并不会少.(不相信的可以试试)
2. 将图片从本地读到内存时,进行压缩 ,即图片从File形式变为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; }
view plaincopy
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 < h && h > 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;
- BitmapFactory.Options op = new BitmapFactory.Options();
- // 开始读入图片,此时把options.inJustDecodeBounds 设回true了
- op.inJustDecodeBounds = true;
- Bitmap bitmap = BitmapFactory.decodeFile(srcPath, op);
- op.inJustDecodeBounds = false;
- // 缩放图片的尺寸
- float w = op.outWidth;
- float h = op.outHeight;
- float hh = 1024f;//
- float ww = 1024f;//
- // 最长宽度或高度1024
- float be = 1.0f;
- if (w > h && w > ww) {
- be = (float) (w / ww);
- } else if (w < h && h > hh) {
- be = (float) (h / hh);
- }
- if (be <= 0) {
- be = 1.0f;
- }
- op.inSampleSize = (int) be;// 设置缩放比例,这个数字越大,图片大小越小.
- // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了
- bitmap = BitmapFactory.decodeFile(srcPath, op);
- int desWidth = (int) (w / be);
- int desHeight = (int) (h / be);
- bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
- try {
- fos = new FileOutputStream(desPath);
- if (bitmap != null) {
- bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
- }
需要注意两个问题:
一、调用getDrawingCache()前先要测量,否则的话得到的bitmap为null,这个我在OnCreate()、OnStart()、OnResume()方法里都试验过。
二、当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色,如下图:
这时只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下图:
在实际开发中,有时候我们需求将文件转换为字符串,然后作为参数进行上传。
必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.util.Base64;
- import java.io.ByteArrayOutputStream;
- /**
- *
- *
- * 功能描述:Android开发之常用必备工具类图片bitmap转成字符串string与String字符串转换为bitmap图片格式
- */
- public class BitmapAndStringUtils {
- /**
- * 图片转成string
- *
- * @param bitmap
- * @return
- */
- public static String convertIconToString(Bitmap bitmap)
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
- byte[] appicon = baos.toByteArray();// 转为byte数组
- return Base64.encodeToString(appicon, Base64.DEFAULT);
- }
- /**
- * string转成bitmap
- *
- * @param st
- */
- public static Bitmap convertStringToIcon(String st)
- {
- // OutputStream out;
- Bitmap bitmap = null;
- try
- {
- // out = new FileOutputStream("/sdcard/aa.jpg");
- byte[] bitmapArray;
- bitmapArray = Base64.decode(st, Base64.DEFAULT);
- bitmap =
- BitmapFactory.decodeByteArray(bitmapArray, 0,
- bitmapArray.length);
- // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
- return bitmap;
- }
- catch (Exception e)
- {
- return null;
- }
- }
- }
如果你的图片是File文件,可以用下面代码:
- /**
- * 图片文件转换为指定编码的字符串
- *
- * @param imgFile 图片文件
- */
- public static String file2String(File imgFile) {
- InputStream in = null;
- byte[] data = null;
- //读取图片字节数组
- try{
- in = new FileInputStream(imgFile);
- data = new byte[in.available()];
- in.read(data);
- in.close();
- } catch (IOException e){
- e.printStackTrace();
- }
- //对字节数组Base64编码
- BASE64Encoder encoder = new BASE64Encoder();
- String result = encoder.encode(data);
- return result;//返回Base64编码过的字节数组字符串
- }
Android图片压缩(质量压缩和尺寸压缩)Bitmap转成字符串上传相关推荐
- 【jquery】通过降低图片的质量(或尺寸)压缩图片大小
生产上图片太大除了用户体验不好,上传等待时间过长,还可能会引发用户缓存丢失,导致必要参数缺失请求失败,或者超时引起的请求失败,查找资料,原理是经过一系列的转化过程file文件=>base64=& ...
- android中的图片选择器,实现微信发布朋友圈多图选择上传功能
本片文章是根据项目要求的思路去学习其他的博主改良的思路,思路会有雷同,但是该文确实属于本人原文创作,参考链接会在文章最后展示(啊啊啊啊啊,好官方....) 先说一下项目的功能要求,类似于QQ和微信在举 ...
- Android 电子签名,手写签名案列实现方法,并上传网页显示(base64)!
最近说项目可能会用到一个电子签名,不需要识别的那种,只是一个单纯手写签名,然后以base64的格式提供给前端web页面.其实挺简单的,自定义一个手写view就上线了.Android 电子签名,手写签名 ...
- java实现图片合成gif图——输出到具体路径或流数据上传
一.多图片转gif 转存到输出流 /*** 多图片转gif 转存到输出流** @param imageList* @param os* @throws IOException*/private sta ...
- 个人界面 头像 图片选择(相册,拍照)--如何调用系统的相册,裁剪并且上传
##需求:个人界面的,个人头像图片的切换 方式一:点击开始切换头像的pop–相册选择 二:这里有两种方式,从相册选择和直接拍照,假设现在是从相册选择选择头像 *我在pop确定的点击方法中写了一个方法- ...
- android过滤文件删除,Android Studio Git 过滤(忽略)和移除不必要上传的文件
1.过滤不需要上传的文件 Android studio 项目中有文件.gitignore文件 内部例如:/.idea/ /.gradle/ /.settings/ /build/ .gitignore ...
- Android 图片选择和拍照(剪辑)及压缩问题 工具类
图片选择和拍照在开发过程中,会遇到不少坑: 1.版本4.4以后选择图片后不会返回绝对路径,但返回Uri,要再查询一次 2.去剪辑时,设置了true的话直接返回bitmap,可能会很占内存,有些机子会挂 ...
- 余额 微信钱包图片_微信红包技巧:关闭这个功能,不上传身份证也能正常使用!...
先点击"论人生吧",再点击"关注",这样您就可以免费收到我们的最新内容了,每天都会有更新,完全是免费订阅,请放心关注.本文转自网络,著作权属归原创者所有.如有侵 ...
- 性能优化之图片压缩(质量压缩、尺寸压缩)
前言 作为开发者的我们,经常会做一些上传图片和和保存图片啦 但是由于一些图片非常大,我们在上传或者保存的时候会占用大量的网络资源和本地资源,那么我们需要做的就是对图片就行压缩.以下介绍常见的两种压缩方 ...
最新文章
- 涨姿势,Java中New一个对象是个怎么样的过程?
- 智能合约的核心思想、语法重点、编程模式、示例、规范及架构
- Math.Round()——面试题小结
- python是一种语言吗-Python是一种什么样的编程语言?解释?编译?汇编?机械?...
- 学习速率 learning rate
- netcore dapper mysql_.NET Core Dapper操作mysql数据库
- SpringBoot中使用thymeleaf时ajax请求不能回显消息
- plsql(轻量版)_基本语法
- could not change product header data even after switching to change mode
- Kubernetes集群(概念篇)
- 就算忘了自己也忘不了你
- ARM处理器是有益补充
- Python 源程序的基本概念
- Flash遮罩之溜光字制作二
- matlab数字转换罗马数字,罗马数字(1到1000) 1到1000的叠加是多少
- 淘客返利机器人,淘宝,拼多多,京东三合一查券返利机器人搭建教程
- 常见英文语法错误案例分享
- 转载文章-【工具】10分钟快速搭建属于自己的文档网站-来自掘金
- 2566420-12-8,TCO-PEG3-alcohol羟基允许发生额外反应以进一步衍生化合物
- MySQL字段名获取