我有一个相机活动。我的活动将拍照,然后我有一个AsyncTask来将照片保存到设备上。以下是我的代码:
class SavePhotoTask extends AsyncTask<byte[], String, String> {
private ProgressDialog dialog;
// protected Context applicationContext;
@Override
public void onPreExecute() {
dialog = new ProgressDialog(CameraPreviewActivity.this);
dialog.setMessage("gravando...");
dialog.show();
}
@Override
protected String doInBackground(byte[]... jpeg) {
try {
int i =jpeg[0].length;
System.out.println("byte array size"+i);
String timeStamp = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
Random generator2 = new Random(10000);
int r=generator2.nextInt(99999);
File cacheDir = getDir(DIRECTORIO, Context.MODE_PRIVATE);
String filename = timeStamp+"-" +r+ ".jpg";
File file = new File(cacheDir, filename);
FileOutputStream stream = new FileOutputStream(file);
//FileOutputStream fos = new FileOutputStream(photo.getPath());
stream.write(jpeg[0]);
stream.close();
long t=file.length();
System.out.println("file size"+t);
} catch (java.io.IOException e) {
Log.e("PictureDemo", "Exception in photoCallback", e);
}
return (null);
}
@Override
protected void onPostExecute(String result) {
this.dialog.cancel();
}
}
这个类是从CommonsWare书籍(Android高级开发)中修改而来。
SavePhotoTask接收以字节数组(byte[])格式的图像,并将其保存到文件中。我想要做的是将其调整大小(小于150K),然后保存它(如果可能的话)。我知道我可以创建位图,但是有没有一种直接压缩字节数组的方法?或者我可以使用其他类。
这是调整位图大小的代码:
Bitmap thumbnail=BitmapFactory.decodeByteArray(jpeg[0], 0, jpeg[0].length)
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.close();
long t=file.length();
if(t>Constants.MAX_FILE_SIZE){
stream = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.JPEG, 75, stream);
stream.close();
t=file.length();
int i=50;
while(t>Constants.MAX_FILE_SIZE && i>=0){
stream = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.JPEG, i, stream);
stream.close();
i=i-5;
t=file.length();
}
}
有没有办法我可以创建更好的东西,当然要使用最少的内存资源。非常感谢。