Java 如何在Android上的MediaStore.Images.Media选定图像后调整图像大小
我目前已成功将移动应用程序中的图像上载到服务器。 我试图找出如何调整图像大小,并可能在发送到服务器之前创建一个缩略图。我在网上找到了很多方法,但都不管用 下面是到目前为止我的代码Java 如何在Android上的MediaStore.Images.Media选定图像后调整图像大小,java,android,Java,Android,我目前已成功将移动应用程序中的图像上载到服务器。 我试图找出如何调整图像大小,并可能在发送到服务器之前创建一个缩略图。我在网上找到了很多方法,但都不管用 下面是到目前为止我的代码 filePath = data.getData(); try { bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
public void uploadMultipart() {
SessionHandler mySession = new SessionHandler(this);
User user = mySession.getUserDetails();
String title = editText.getText().toString().trim();
String path = getPath(filePath);
String studentid = user.studentid;
String email = user.email;
String firstname = user.firstname;
//Toast.makeText(this, firstname, Toast.LENGTH_SHORT).show();
try {
String uploadId = UUID.randomUUID().toString();
uploadReceiver.setDelegate(this);
uploadReceiver.setUploadID(uploadId);
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image")
.addParameter("title", title)
.addParameter("studentid", studentid)
.addParameter("firstname", firstname)
.addParameter("email", email)
//.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
要压缩图像,请在活动中写入此方法
public void compressImage(String filePath) {
try {
OutputStream outStream = null;
Log.i("filePath",filePath);
outStream = new FileOutputStream(filePath);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 8;
bitmap = BitmapFactory.decodeFile(filePath ,bmOptions);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outStream);
outStream.flush();
outStream.close();
Log.i("file path compress", filePath);
} catch (Exception e) {
Log.i("exception", e.toString());
}
}
并在活动结果中调用它
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == TAKE_PHOTO){ //your request code
filePath = data.getData();
try {
compressImage(filePath);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
您可以使用compressImage方法对图像进行任意压缩
public Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(
bitmap, 0, 0, width, height, matrix, false);
bitmap.recycle();
return resizedBitmap;
}你说的我都做了,但由于某种原因,没有调整大小。文件已上载,但未进行压缩。