【发布时间】:2013-12-13 16:25:59
【问题描述】:
我正在使用此 AsyncTask 将我的图像资源保存到 SD 卡:
public class SaveImageAsync extends AsyncTask<String, String, String> {
private Context mContext;
int imageResourceID;
private ProgressDialog mProgressDialog;
public SaveImageAsync(Context context, int image)
{
mContext = context;
imageResourceID = image;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setMessage("Saving Image to SD Card");
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
@SuppressLint("NewApi")
@Override
protected String doInBackground(String... filePath) {
try {
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), imageResourceID);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bitmapdata);
int lenghtOfFile = bitmap.getByteCount();
Log.d("LOG", "File Lenght = " + lenghtOfFile);
byte[] buffer = new byte[64];
int len1 = 0;
long total = 0;
while ((len1 = bis.read(buffer)) > 0) {
total += len1;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
bos.write(buffer, 0, len1);
}
bos.flush();
bos.close();
bitmap.recycle();
bis.close();
return getTempUri().getPath();
} catch (Exception e) {
return null;
}
}
protected void onProgressUpdate(String... progress) {
mProgressDialog.setIndeterminate(false);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(String filename) {
// dismiss the dialog after the file was saved
try {
mProgressDialog.dismiss();
mProgressDialog = null;
} catch (Exception e) {
e.printStackTrace();
}
}
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File directory = new File(mContext.getExternalCacheDir().getPath());
directory.mkdirs();
File file = new File(directory , "temp.jpg");
try {
file.createNewFile();
} catch (IOException e) {}
return file;
} else {
return null;
}
}
}
我从我的活动中调用它:
new SaveImageAsync(this, R.drawable.my_image_resource).execute();
它工作正常,问题是bitmap.getByteCount();返回的位图大小与保存文件的最终大小完全不同。过程完成时的结果,指示的进度仅多或少 20%。
有什么方法可以在保存之前知道文件的最终大小?谢谢。
【问题讨论】:
标签: android bitmap android-asynctask progressdialog sd-card