你好我有以下代码从画廊活动中获取图像,我希望图像在上传之前被平方到特定尺寸400 * 400,同时保持其宽高比,以便所有上传的图像大小相同。任何想法,请
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
assert selectedImage != null;
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgPath = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = findViewById(R.id.imagebutton);
int width = imgView.getWidth();
int height = imgView.getHeight();
Bitmap bitmap = Bitmap.createScaledBitmap(BitmapFactory.decodeFile(imgPath),width, height, false);
imgView.setImageBitmap(bitmap);
// Get the Image's file name
String fileNameSegments[] = imgPath.split("/");
fileName = fileNameSegments[fileNameSegments.length - 1];
// Put file name in Async Http Post Param which will used in Php web app
params.put("filename", fileName);
} else {
Toast.makeText(this, R.string.noimageselected,
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, R.string.erroroccurred, Toast.LENGTH_LONG)
.show();
}
}
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
答案 0 :(得分:1)
在上传图片之前添加此代码以调整图片大小
int newWidth=400;
int newHeight=400;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap , newWidth, newHeight, true);
@Override
protected String doInBackground(Void... params) {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap = BitmapFactory.decodeFile(imgPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
//Add these lines
int newWidth=400;
int newHeight=400;
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap , newWidth, newHeight, true);
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}