图片压缩质量压缩,比例压缩,采样率压缩,JPEG压缩
思路:根据控件的尺寸或图片要放大显示的尺寸作为参数去压缩图片
原图为6M,以下是各种压缩的效果
![](https://img.haomeiwen.com/i6059826/5f98937f79993255.png)
以下贴出代码:
质量压缩
/**
* 质量压缩
*
* @param bitmap 要压缩的bitmap
* @param quality 要压缩的质量系数,范围0-100,越小压缩率越高
*/
public Bitmap getCompressBitmapByQuality(Bitmap bitmap, int quality) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, bos);
return BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.toByteArray().length);
}
比例压缩
/**
* 比例压缩
*/
private Bitmap getCompressBitmapByScale(Bitmap bitmap, int maxW, int maxH) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
float sx = (float) maxW / (float) w;
float sy = (float) maxH / (float) h;
Matrix matrix = new Matrix();
matrix.setScale(sx, sy);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
}
采样率压缩
/**
* 采样率压缩
*/
private Bitmap getCompressBitmapBySampleSize(Bitmap bitmap, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
return BitmapFactory.decodeByteArray(bos.toByteArray(), 0,
bos.toByteArray().length, options);
}
JPEG压缩
/**
* 使用so来压缩图片
*/
public void compressImage(View view) {
// Android Q中会将文件存储到该应用的沙盒文件路径下,不需要申请文件读写的权限
File picturePath = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String path = picturePath + File.separator + "compressImg";
Log.i("TAG", " 路径:" + path);
//沙盒下创建文件夹
File file = new File(path);
if (file.exists() || file.mkdirs()) {
//BitmapFactory.Options options = new BitmapFactory.Options();
//Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tm2);
//options.inJustDecodeBounds = false;
//Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.tm2, options);
Bitmap bitmap = readBitmap();
ImageCompress compress = new ImageCompress();
long start = System.currentTimeMillis();
String imgPath = path + File.separator + "compressSo.jpg";
int i = compress.compressBitmap(bitmap, 30, imgPath);
if (i == 1) {
long l = System.currentTimeMillis() - start;
Log.i("TAG", " 压缩并存储成功 耗时:" + l);
} else {
Log.i("TAG", " 压缩并存储失败");
}
}
}
package com.example.image;
import android.graphics.Bitmap;
import java.nio.ByteBuffer;
public class ImageCompress {
static {
System.loadLibrary("imageCompress");
}
/**
* NDK方法加载图片
*
* @param bitmap 图片bitmap
* @param quality 压缩的质量
* @param fileName 压缩后的路径
* @return
*/
public native int compressBitmap(Bitmap bitmap, int quality,
String fileName);
public native ByteBuffer getImage(String fileName);
public native ByteBuffer getImage2(Bitmap bitmap, int quality);
public native void release(ByteBuffer byteBuffer);
}
项目的地址:
网友评论