Android:图像压缩时会出现黑色背景,但不会降低质量
下面是我用于图像压缩的类文件,它工作得很好,但问题是当我使用低分辨率图像时,输出图像以黑色背景绘制。有人能告诉我哪里需要更改吗Android:图像压缩时会出现黑色背景,但不会降低质量,android,canvas,bitmap,compression,Android,Canvas,Bitmap,Compression,下面是我用于图像压缩的类文件,它工作得很好,但问题是当我使用低分辨率图像时,输出图像以黑色背景绘制。有人能告诉我哪里需要更改吗 public class CompressImage { public static Context context; /** * @function returnCompressImage() - will return the compressed Image Path * @param mContext * @param imageUri * @ret
public class CompressImage {
public static Context context;
/**
* @function returnCompressImage() - will return the compressed Image Path
* @param mContext
* @param imageUri
* @return
*/
public static String returnCompressImage(Context mContext, String imageUri, int imageId, int optionId) {
context = mContext;
String filePath = getRealPathFromURI(context, imageUri);
String compressImageFilePath = "";
Bitmap scaledBitmap = null;
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;
Bitmap bmp = BitmapFactory.decodeFile(filePath, options);// actual bitmap
// File mFile = new File(filePath);
// long fileSize = mFile.length() / 1024;
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
// max Height and width values of the compressed image is taken as 800x480
float maxHeight = 816.0f;
float maxWidth = 612.0f;
float imgRatio = actualWidth / actualHeight;
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(filePath, 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);
// Fill with white
// canvas.drawColor(Color.WHITE);
Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
float tempLeft = middleX - bmp.getWidth() / 2;
float tempRight = middleY - bmp.getHeight() / 2;
canvas.drawBitmap(bmp, tempLeft, tempRight, mPaint);
// check the rotation of the image and display it properly
ExifInterface exif;
try {
exif = new ExifInterface(filePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Log.d("EXIF", "Exif: " + orientation);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 3) {
matrix.postRotate(180);
Log.d("EXIF", "Exif: " + orientation);
} else if (orientation == 8) {
matrix.postRotate(270);
Log.d("EXIF", "Exif: " + orientation);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream out = null;
compressImageFilePath = getFilename(imageId, optionId);
try {
out = new FileOutputStream(compressImageFilePath);
// write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 45, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("compressedFileName", compressImageFilePath);
return compressImageFilePath;
}
public static String getFilename(int imageId, int optionId) {
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("MyPictures", Context.MODE_PRIVATE);
File file = new File(directory, imageId + "_opt" + optionId + ".jpg");
String uriSting = (file.getAbsolutePath());
return uriSting;
}
public static File getFile(int imageId, int optionId) {
ContextWrapper cw = new ContextWrapper(context);
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("MyPicture", Context.MODE_PRIVATE);
File file = new File(directory, imageId + "_opt" + optionId + ".jpg");
// String uriSting = (file.getAbsolutePath());
return file;
}
@SuppressLint("NewApi")
public static int sizeOf(Bitmap data) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
return data.getRowBytes() * data.getHeight();
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
return data.getByteCount();
} else {
return data.getAllocationByteCount();
}
}
private static String getRealPathFromURI(Context context, String contentURI) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = context.getContentResolver().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(index);
}
}
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;
Log.d("totalPixels :", "" + totalPixels);
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
Log.d("totalReqPixelsCap :", "" + totalReqPixelsCap);
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}}
公共类压缩图像{
公共静态语境;
/**
*@function returnCompressImage()-将返回压缩图像路径
*@param mContext
*@param-imageUri
*@返回
*/
公共静态字符串returnCompressImage(上下文mContext、字符串imageUri、int imageId、int optionId){
上下文=mContext;
字符串filePath=getRealPathFromURI(上下文,imageUri);
字符串compressImageFilePath=“”;
位图缩放位图=空;
BitmapFactory.Options=new-BitmapFactory.Options();
//通过将此字段设置为true,实际位图像素不会加载到内存中。只加载边界。如果
//如果您尝试在此处使用位图,将得到null。
options.inJustDecodeBounds=true;
位图bmp=BitmapFactory.decodeFile(文件路径,选项);//实际位图
//File mFile=新文件(filePath);
//long fileSize=mFile.length()/1024;
int实际高度=options.outHeight;
int actualWidth=options.outWidth;
//压缩图像的最大高度和宽度值取800x480
浮动最大高度=816.0f;
浮动最大宽度=612.0f;
浮动高度=实际宽度/实际高度;
浮点最大比值=最大宽度/最大高度;
//设置宽度和高度值以保持图像的纵横比
如果(实际高度>最大高度| |实际宽度>最大宽度){
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);
//充满白色
//画布。drawColor(颜色。白色);
Paint mPaint=新油漆(油漆.过滤器\u位图\u标志);
float tempLeft=middleX-bmp.getWidth()/2;
float tempRight=middleY-bmp.getHeight()/2;
drawBitmap(bmp、tempLeft、tempRight、mPaint);
//检查图像的旋转并正确显示
出口接口;
试一试{
exif=新的ExifInterface(文件路径);
int-orientation=exif.getAttributeInt(ExifInterface.TAG_-orientation,0);
Log.d(“EXIF”,“EXIF:+方向”);
矩阵=新矩阵();
如果(方向==6){
矩阵旋转后(90);
Log.d(“EXIF”,“EXIF:+方向”);
}否则如果(方向==3){
矩阵旋转后(180);
Log.d(“EXIF”,“EXIF:+方向”);
}否则如果(方向==8){
矩阵旋转后(270);
Log.d(“EXIF”,“EXIF:+方向”);
}
scaledBitmap=Bitmap.createBitmap(scaledBitmap,0,0,scaledBitmap.getWidth(),scaledBitmap.getHeight(),矩阵,true);
}捕获(IOE异常){
e、 printStackTrace();
}
FileOutputStream out=null;
compressImageFilePath=getFilename(图像ID,选项ID);
试一试{
out=新文件输出流(compressImageFilePath);
//在文件名指定的目标位置写入压缩位图。
scaledBitmap.compress(Bitmap.CompressFormat.JPEG,45,out);
}catch(filenotfounde异常){
e、 printStackTrace();
}
d(“compressedFileName”,compressImageFilePath);
返回压缩文件路径;
}
公共静态字符串getFilename(int-imageId,int-optionId){
ContextWrapper cw=新的ContextWrapper(上下文);
///data/data/yourapp/app_data/imageDir的路径
File directory=cw.getDir(“MyPictures”,Context.MODE\u PRIVATE);
File File=新文件(目录,imageId+“_opt”+optionId+”.jpg”);
字符串uriSting=(file.getAbsolutePath());
回归分析;
}
公共静态文件getFile(int-imageId,int-optionId){
ContextWrapper cw=新的ContextWrapper(上下文);
///data/data/yourapp/app_data/imageDir的路径
File directory=cw.getDir(“MyPicture”,Context.MODE\u PRIVATE);
File File=新文件(目录,imageId+“_opt”+optionId+”.jpg”);
//字符串uriSting=(file.getAbsolutePath());
返回文件;
}
@SuppressLint(“新API”)
公共静态int-sizeOf(位图数据){
if(Build.VERSION.SDK\u INTimageView.setImageBitmap(BitmapUtility.decodeSampledBitmapFromResource(picturePath,400,400));
public class BitmapUtility {
public static Bitmap decodeSampledBitmapFromResource(String path,int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path,options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
private 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;
}
}