我有一个关于缩小图像库中所选图像的问题,以便我可以通过 php 将其上传到服务器。
所以行动顺序是:
1)从图库中获取选定的图像(完成)
2)缩小并压缩为jpg(卡在这里)
3)异步上传到服务器(完成)
我需要连接第一步和第三步。到目前为止我已经这样做了:
获取选定的图像:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(picturePath);
new async_upload().execute(picturePath.toString());
}
}
异步上传:
public class async_upload extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... arg0) {
uploadFile(arg0[0]);
return "asd";
}
@Override
protected void onPostExecute(String result) {
}
}
public int uploadFile(String sourceFileUri) {
..............Code for uploading works.......
}
我的功能是缩小图像。
private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 640;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);
}
如您所见,我将所选图像的 URI 发送至uploadFile
异步上传。
我的问题是如何“制作所选图像的副本”、压缩/缩放并发送该图像而不是原始图像。当然,我不想改变用户的图像......但发送缩放版本。
有任何想法吗?
谢谢你!