一个好用的android图片压缩工具类 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 技术分享 >

一个好用的android图片压缩工具类

发表时间:2020-10-19

发布人:葵宇科技

浏览次数:15




<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">用了良久图片紧缩,之前人们一向应用google的官方图片紧缩办法</span>

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 static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

代率攀来自google 
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
细心看calucelateInSamplesize办法,该算法返回的是一种紧缩比例,细心一看他的计算过程,你会发明,inSampleSize的变更过程是2-4-8,,而真正进入wile轮回时,宽高就已经被算作是小了一笆攀来计算的了,所以,膳绫擎那个网站说12M能紧缩到0.75M,就是因为差距太大年夜,如不雅安卓手机内部紧缩本身的图片(大年夜概是2M紧缩到100K),所以此时,这个办法就实用于android编码紧缩了。
所以不才针对于android编码时紧缩,在此对它进行了优化,优化后代码如下:
运行:   culculateInSampleSize(bm,200,300)效不雅:
<pre name="code" class="java"><span style="font-family: Arial, Helvetica, sans-serif;">/**</span>
* 盘似揭捉缩比例值(改进版 by touch_ping)

* 原版2>4>8...倍紧缩
* 当前2>3>4...倍紧缩

* @param options
*            解析图片的设备信息
* @param reqWidth
*            所需图片紧缩尺寸最小宽度
* @param reqHeight
*            所需图片紧缩尺寸最小高度
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {

final int picheight = options.outHeight;
final int picwidth = options.outWidth;
Log.i("test", "原尺寸:" +  picwidth + "*" +picheight);

int targetheight = picheight;
int targetwidth = picwidth;
int inSampleSize = 1;

if (targetheight > reqHeight || targetwidth > reqWidth) {
while (targetheight  >= reqHeight
&& targetwidth>= reqWidth) {
Log.i("test","紧缩:" +inSampleSize + "倍");
inSampleSize += 1;
targetheight = picheight/inSampleSize;
targetwidth = picwidth/inSampleSize;
}
}

Log.i("test","最终紧缩比例:" +inSampleSize + "倍");
Log.i("test", "新尺寸:" +  targetwidth + "*" +targetheight);
return inSampleSize;
}


紧缩效不雅如下:
[img]
文件大年夜小大年夜1.12M变成81.75k
最终附上完全紧缩对象类:
package com.example.mqtest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * 图片紧缩对象类
 * @author touch_ping
 * 2015-1-5 下昼1:29:59
 */
public class BitmapCompressor {
	/**
	 * 质量紧缩
	 * @author ping 2015-1-5 下昼1:29:58
	 * @param image
	 * @param maxkb
	 * @return
	 */
	public static Bitmap compressBitmap(Bitmap image,int maxkb) {
		//L.showlog("紧缩图片");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 质量紧缩办法,这里100表示不紧缩,把紧缩后的数据存放到baos中
		int options = 100;
//		Log.i("test","原始大年夜小" + baos.toByteArray().length);
		while (baos.toByteArray().length / 1024 > maxkb) { // 轮回断定如不雅紧缩后图片是否大年夜于(maxkb)50kb,大年夜于持续紧缩
//			Log.i("test","紧缩一次!");
			baos.reset();// 重置baos即清空baos
			options -= 10;// 每次都削减10
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里紧缩options%,把紧缩后的数据存放到baos中
		}
//		Log.i("test","紧缩后大年夜小" + baos.toByteArray().length);
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把紧缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}
	
	/**
	 * http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
	 * 官网:获取紧缩后的图片
	 * 
	 * @param res
	 * @param resId
	 * @param reqWidth
	 *            所需图片紧缩尺寸最小宽度
	 * @param reqHeight
	 *            所需图片紧缩尺寸最小高度
	 * @return
	 */
	public static 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);
	}

	/**
	 * 官网:获取紧缩后的图片
	 * 
	 * @param res
	 * @param resId
	 * @param reqWidth
	 *            所需图片紧缩尺寸最小宽度
	 * @param reqHeight
	 *            所需图片紧缩尺寸最小高度
	 * @return
	 */
	public static Bitmap decodeSampledBitmapFromFile(String filepath,
			int reqWidth, int reqHeight) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filepath, options);

		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filepath, options);
	}

	public static Bitmap decodeSampledBitmapFromBitmap(Bitmap bitmap,
			int reqWidth, int reqHeight) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
		byte[] data = http://www.sjsjw.com/100/000202MYM011683/baos.toByteArray();
		
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeByteArray(data, 0, data.length, options);
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeByteArray(data, 0, data.length, options);
	}

	/**
	 * 盘似揭捉缩比例值(改进版 by touch_ping)
	 * 
	 * 原版2>4>8...倍紧缩
	 * 当前2>3>4...倍紧缩
	 * 
	 * @param options
	 *            解析图片的设备信息
	 * @param reqWidth
	 *            所需图片紧缩尺寸最小宽度O
	 * @param reqHeight
	 *            所需图片紧缩尺寸最小高度
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		
		final int picheight = options.outHeight;
		final int picwidth = options.outWidth;
		Log.i("test", "原尺寸:" +  picwidth + "*" +picheight);
		
		int targetheight = picheight;
		int targetwidth = picwidth;
		int inSampleSize = 1;
		
		if (targetheight > reqHeight || targetwidth > reqWidth) {
			while (targetheight  >= reqHeight
					&& targetwidth>= reqWidth) {
				Log.i("test","紧缩:" +inSampleSize + "倍");
				inSampleSize += 1;
				targetheight = picheight/inSampleSize;
				targetwidth = picwidth/inSampleSize;
			}
		}
		
		Log.i("test","最终紧缩比例:" +inSampleSize + "倍");
		Log.i("test", "新尺寸:" +  targetwidth + "*" +targetheight);
		return inSampleSize;
	}
}

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

相关案例查看更多