我读了很多主题,其中位图通过decodeFile和createScaledBitmap调整大小。但我想更改此文件,而不创建额外的位图或文件。这意味着,就在我打开这个文件时,位图会更小/更大。有可能吗?
编辑: 具体来说,我有jpeg文件,我将压缩这些文件,在制作zip之前我设置了图像大小(在zip文件中)。
答案 0 :(得分:0)
如果您只想将其作为自身的较小版本打开,则可以使用BitmapFactory.Options.inSampleSize
来减少负载大小。如果您想实际调整图像大小并将其重新保存到文件系统,您需要在AsyncTask中执行此操作,
类似的东西:
public class ImageResizerTask extends AsyncTask<Integer, Void, Bitmap> {
Bitmap mBitmap;
String filePath;
Context mContext;
Activity mCallBack;
//ProgressDialog pd;
public ImageResizerTask(Context context, String path,
Activity callBack) {
mContext = context;
filePath = path;
mBitmap = BitmapFactory.decodeFile(filePath);
mCallBack = callBack;
}
@Override
protected void onPreExecute() {
}
@Override
protected Bitmap doInBackground(Integer... params) {
// TODO Auto-generated method stub
resize(mBitmap);
return mBitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
//pd.dismiss();
bitmap.recycle();
mCallBack.onImageResized(filePath);
}
private void resize(Bitmap tmp) {
final Bitmap bitmap = Bitmap.createBitmap(500, 500,
Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
Log.v("TMPBMP",
"temp bmp width:" + tmp.getWidth() + " height:"
+ tmp.getHeight());
if (tmp.getWidth() < tmp.getHeight()) {
final int width = (int) (1f * tmp.getWidth() / tmp.getHeight() * 500);
final int height = 500;
final Bitmap scaled = Bitmap.createScaledBitmap(tmp, width, height,
false);
final int leftOffset = (bitmap.getWidth() - scaled.getWidth()) / 2;
final int topOffset = 0;
canvas.drawBitmap(scaled, leftOffset, topOffset, null);
} else {
final int width = 500;
final int height = (int) (1f * tmp.getHeight() / tmp.getWidth() * 500);
;
final Bitmap scaled = Bitmap.createScaledBitmap(tmp, width, height,
false);
final int leftOffset = 0;
final int topOffset = (bitmap.getHeight() - scaled.getHeight()) / 2;
canvas.drawBitmap(scaled, leftOffset, topOffset, null);
}
FileOutputStream outStream;
try {
outStream = new FileOutputStream(filePath);
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
我不清楚,你想要获得什么, 但这是一个调整图像文件大小的简单代码
String your_file_path = "image.png";
int set_scale_your_need = 2;
//getting your image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(your_file_path, o);
o.inJustDecodeBounds = false;
o.inSampleSize = set_scale_your_need;
Bitmap bitmap = BitmapFactory.decodeFile(your_file_path, o);
FileOutputStream fos = new FileOutputStream(your_file_path, false);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();