Java 内存有效的图像处理方法?
我有一些代码可以拍摄两个图像,并将它们的中间部分合并到一个图像中。该代码可以工作,但占用了大量内存,因此在一些内存不足的设备上会出现故障 有什么方法可以提高代码的内存效率吗 代码Java 内存有效的图像处理方法?,java,android,android-canvas,android-image,android-bitmap,Java,Android,Android Canvas,Android Image,Android Bitmap,我有一些代码可以拍摄两个图像,并将它们的中间部分合并到一个图像中。该代码可以工作,但占用了大量内存,因此在一些内存不足的设备上会出现故障 有什么方法可以提高代码的内存效率吗 代码 你可以试试压缩。尝试此有用的imagecompressor类,为方便起见复制并粘贴到此线程中: java压缩器会将图片压缩到其大小的1/10左右,因此对于3mb图片,它将变成300kb。希望这能为你节省一些记忆 import android.content.Context; import android.graphi
你可以试试压缩。尝试此有用的imagecompressor类,为方便起见复制并粘贴到此线程中: java压缩器会将图片压缩到其大小的1/10左右,因此对于3mb图片,它将变成300kb。希望这能为你节省一些记忆
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import timber.log.Timber;
//http://voidcanvas.com/whatsapp-like-image-compression-in-android/
public class ImageCompressor {
public ImageCompressor() {}
public static String compressImage(String imagePath, Context context) {
Bitmap scaledBitmap = null;
String filename = "compressed_" +imagePath.substring(imagePath.lastIndexOf("/")+1);
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Timber.e( "imagePath "+imagePath);
Timber.e("filename "+filename);
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
if (options == null) {
Timber.e("zero bitmap");
}
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = actualWidth / actualHeight;
float maxHeight = actualHeight * 10/20;
float maxWidth = actualWidth * 10/20;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Timber.e("Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Timber.e( "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Timber.e( "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Timber.e( "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = context.openFileOutput(filename, Context.MODE_PRIVATE);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; }
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
}
导入android.content.Context;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.graphics.Canvas;
导入android.graphics.Matrix;
导入android.graphics.Paint;
导入android.media.ExifInterface;
导入java.io.FileNotFoundException;
导入java.io.FileOutputStream;
导入java.io.IOException;
进口木材;
//http://voidcanvas.com/whatsapp-like-image-compression-in-android/
公共级图像压缩程序{
公共图像压缩程序(){}
公共静态字符串压缩图像(字符串图像路径、上下文){
位图缩放位图=空;
String filename=“compressed\”+imagePath.substring(imagePath.lastIndexOf(“/”)+1);
BitmapFactory.Options=new-BitmapFactory.Options();
//通过将此字段设置为true,实际位图像素不会加载到内存中。只加载边界。如果
//如果您尝试在此处使用位图,将得到null。
options.inJustDecodeBounds=true;
木材。e(“imagePath”+imagePath);
e(“文件名”+文件名);
位图bmp=BitmapFactory.decodeFile(图像路径,选项);
如果(选项==null){
Timber.e(“零位图”);
}
int实际高度=options.outHeight;
int actualWidth=options.outWidth;
浮动高度=实际宽度/实际高度;
浮动最大高度=实际高度*10/20;
浮动最大宽度=实际宽度*10/20;
浮点最大比值=最大宽度/最大高度;
//设置宽度和高度值以保持图像的纵横比
如果(实际高度>最大高度| |实际宽度>最大宽度){
if(imgRatiomaxRatio){
imgRatio=最大宽度/实际宽度;
实际高度=(int)(imgRatio*实际高度);
实际宽度=(int)最大宽度;
}否则{
实际高度=(int)最大高度;
实际宽度=(int)最大宽度;
}
}
//设置inSampleSize值允许加载原始图像的缩小版本
options.inSampleSize=calculateInSampleSize(选项、实际宽度、实际高度);
//inJustDecodeBounds设置为false以加载实际位图
options.inJustDecodeBounds=false;
//此选项允许android在内存不足时声明位图内存
options.inpurgable=true;
options.inInputShareable=true;
options.inTempStorage=新字节[16*1024];
试一试{
//从位图路径加载位图
bmp=BitmapFactory.decodeFile(图像路径,选项);
}捕获(OutOfMemoryError异常){
异常。printStackTrace();
}
试一试{
scaledbimat=Bitmap.createBitmap(实际宽度、实际高度、Bitmap.Config.ARGB_8888);
}捕获(OutOfMemoryError异常){
异常。printStackTrace();
}
浮动比率=实际宽度/(浮动)选项。向外宽度;
浮动比率=实际高度/(浮动)选项。超出高度;
浮动中间点x=实际宽度/2.0f;
浮动中间Y=实际高度/2.0f;
矩阵scaleMatrix=新矩阵();
scaleMatrix.setScale(ratioX、ratioY、middleX、middleY);
画布画布=新画布(缩放位图);
canvas.setMatrix(scaleMatrix);
drawBitmap(bmp,middleX-bmp.getWidth()/2,middleY-bmp.getHeight()/2,新绘制(Paint.FILTER_位图_标志));
//检查图像的旋转并正确显示
出口接口;
试一试{
exif=新的ExifInterface(imagePath);
int-orientation=exif.getAttributeInt(
ExiFinInterface.TAG_方向,0);
木材.e(“进出口银行:+方向”);
矩阵=新矩阵();
如果(方向==6){
矩阵旋转后(90);
木材.e(“进出口银行:+方向”);
}否则如果(方向==3){
矩阵旋转后(180);
木材.e(“进出口银行:+方向”);
}否则如果(方向==8){
矩阵旋转后(270);
木材.e(“进出口银行:+方向”);
}
scaledBitmap=Bitmap.createBitmap(scaledBitmap,0,0,
scaledBitmap.getWidth(),scaledBitmap.getHeight(),矩阵,
正确的);
}捕获(IOE异常){
e、 printStackTrace();
}捕获(NullPointerException e){
e、 printStackTrace();
}
FileOutputStream out=null;
试一试{
out=context.openFileOutput(文件名,context.MODE\u PRIVATE);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG,90,out);
out.close();
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回文件名;
}
公共静态int-calculateInSampleSize(BitmapFactory.Options选项、int-reqWidth、int-reqHeight){
最终内部高度=options.outHeight;
最终int w
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import timber.log.Timber;
//http://voidcanvas.com/whatsapp-like-image-compression-in-android/
public class ImageCompressor {
public ImageCompressor() {}
public static String compressImage(String imagePath, Context context) {
Bitmap scaledBitmap = null;
String filename = "compressed_" +imagePath.substring(imagePath.lastIndexOf("/")+1);
BitmapFactory.Options options = new BitmapFactory.Options();
// by setting this field as true, the actual bitmap pixels are not loaded in the memory. Just the bounds are loaded. If
// you try the use the bitmap here, you will get null.
options.inJustDecodeBounds = true;
Timber.e( "imagePath "+imagePath);
Timber.e("filename "+filename);
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
if (options == null) {
Timber.e("zero bitmap");
}
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = actualWidth / actualHeight;
float maxHeight = actualHeight * 10/20;
float maxWidth = actualWidth * 10/20;
float maxRatio = maxWidth / maxHeight;
// width and height values are set maintaining the aspect ratio of the image
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
// setting inSampleSize value allows to load a scaled down version of the original image
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
// inJustDecodeBounds set to false to load the actual bitmap
options.inJustDecodeBounds = false;
// this options allow android to claim the bitmap memory if it runs low on memory
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
// load the bitmap from its path
bmp = BitmapFactory.decodeFile(imagePath, options);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
try {
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 0);
Timber.e("Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Timber.e( "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Timber.e( "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Timber.e( "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0,
scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix,
true);
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
FileOutputStream out = null;
try {
out = context.openFileOutput(filename, Context.MODE_PRIVATE);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; }
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
}