我的要求是数据库中存储的大小(宽度,高度而不是文件大小)图像,我需要检索图像的简单护照尺寸。
我的代码是:
byte[] imgByte=null;
在oncreate方法中
imageview=new ImageView(this);
imageview.setLayoutParams(llp2);
imgByte=cursor.getBlob(cursor.getColumnIndex("imagestore"));
imageview.setScaleType(ScaleType.CENTER);
imageview.setImageBitmap(BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length));
layout.addView(imageview)
当我显示时,只显示输入之前的尺寸。所以我需要在android中适应该图像大小。
我试过这些链接
Reduce size of Bitmap to some specified pixel in Android
但这里的问题是我在字节中得到了图像。但是所有代码只对图像数据类型为int。我可以得到正确的解决方案,以务实的方式减小图像尺寸吗?
答案 0 :(得分:0)
您可以使用以下代码创建样本大小的图像。这将返回Bitmap
。
public static Bitmap decodeSampledBitmapFromResource(Resources res,
int resId, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
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) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
使用此代码,
decodeSampledBitmapFromResource(getResources(),R.drawable.xyz, 100, 100);
此处,您提供的样本量为100 * 100。因此将创建此类大小的缩略图。
修改强>
要在代码中使用bytes [],请使用以下代码。
public static Bitmap decodeSampledBitmap(byte[] data, int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(data, 0, data.length, options);
}