gpt4 book ai didi

java - 如何在 Android 上 MediaStore.Images.Media 选择图像后调整图像大小

转载 作者:行者123 更新时间:2023-12-01 22:17:11 25 4
gpt4 key购买 nike

我目前已成功将移动应用内的图像上传到服务器。我正在尝试弄清楚如何调整图像大小并可能在将其发送到服务器之前创建缩略图。我尝试了很多网上找到的方法,但没有一个有效。

下面是我到目前为止的代码。

            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();
}
}

最佳答案

要压缩图像,请将此方法写入您的 Activity

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());
}
}

并在您的 Activity 结果中调用它

@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 方法中根据需要压缩图像。

关于java - 如何在 Android 上 MediaStore.Images.Media 选择图像后调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58617634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com