gpt4 book ai didi

android - 在上传之前调整从画廊或相机拍摄的图像的大小

转载 作者:搜寻专家 更新时间:2023-11-01 07:59:06 24 4
gpt4 key购买 nike

我的站点中有一个表单,允许用户上传照片。我的 android 应用程序使用 WebView 允许用户访问该站点。单击上传按钮后,该应用程序允许用户在图库中已存在的图像之间进行选择,或者拍摄新照片并上传该图像。我为此使用的代码是

showAttachmentDialog 由 openFileChooser 调用

private void showAttachmentDialog(ValueCallback<Uri> uploadMsg) {
this.mUploadMessage = uploadMsg;

File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MyApp");
// Create the storage directory if it does not exist
if (! imageStorageDir.exists()){
imageStorageDir.mkdirs();
}
File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");


this.imageUri= Uri.fromFile(file);


final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for(ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
cameraIntents.add(intent);
}


// mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
Intent chooserIntent = Intent.createChooser(intent,"Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
this.startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}

我的 onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {

if (null == this.mUploadMessage) {
return;
}

Uri result;
if (resultCode != RESULT_OK) {
result = null;
} else {
result = intent == null ? this.imageUri : intent.getData(); // retrieve from the private variable if the intent is null
}

this.mUploadMessage.onReceiveValue(result);
this.mUploadMessage = null;



}
}

我希望能够在上传图片之前更改图片的大小,并且我希望这可以在手机上完成,而不是在网页上完成。完成后,我还想从手机中删除调整大小的图像并保留原型(prototype)。你能建议我一个方法吗?我在 SO 中展示了几个案例,其中建议创建位图并使用 createScaledBitmap 将其调整为所需的大小,但我不确定在我的案例中哪种方法最好。这应该在哪里进行?在我的 onActivityResult 中?提前致谢!

--------------------编辑------------------------

私有(private)文件imageStorageDir,文件;

我在我的主 Activity 中声明了这些,并在我的 onActivityResult 中添加了以下 fragment

String newPath=file.getAbsolutePath();
Bitmap bMap= BitmapFactory.decodeFile(newPath);
Bitmap out = Bitmap.createScaledBitmap(bMap, 150, 150, false);
File resizedFile = new File(imageStorageDir, "resized.png");

OutputStream fOut=null;
try {
fOut = new BufferedOutputStream(new FileOutputStream(resizedFile));
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
bMap.recycle();
out.recycle();

} catch (Exception e) { // TODO

}

现在用相机拍照时图像正在调整大小并上传但是当我使用画廊时我得到一个 NullPointerException

05-23 10:12:50.354: E/BitmapFactory(1376): Unable to decode stream: java.io.FileNotFoundException: /storage/sdcard/Pictures/MyApp/IMG_1400854361171.jpg: open failed: ENOENT (No such file or directory)
05-23 10:12:50.364: D/AndroidRuntime(1376): Shutting down VM
05-23 10:12:50.414: W/dalvikvm(1376): threadid=1: thread exiting with uncaught exception (group=0x41465700)
05-23 10:12:50.494: E/AndroidRuntime(1376): FATAL EXCEPTION: main
05-23 10:12:50.494: E/AndroidRuntime(1376): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/76 }} to activity {com.example.sinatra19/com.example.sinatra19.Sinatra22Activity}: java.lang.NullPointerException
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.ActivityThread.deliverResults(ActivityThread.java:3367)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3410)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.ActivityThread.access$1100(ActivityThread.java:141)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1304)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.os.Handler.dispatchMessage(Handler.java:99)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.os.Looper.loop(Looper.java:137)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.ActivityThread.main(ActivityThread.java:5103)
05-23 10:12:50.494: E/AndroidRuntime(1376): at java.lang.reflect.Method.invokeNative(Native Method)
05-23 10:12:50.494: E/AndroidRuntime(1376): at java.lang.reflect.Method.invoke(Method.java:525)
05-23 10:12:50.494: E/AndroidRuntime(1376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
05-23 10:12:50.494: E/AndroidRuntime(1376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-23 10:12:50.494: E/AndroidRuntime(1376): at dalvik.system.NativeStart.main(Native Method)
05-23 10:12:50.494: E/AndroidRuntime(1376): Caused by: java.lang.NullPointerException
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:482)
05-23 10:12:50.494: E/AndroidRuntime(1376): at com.example.sinatra19.Sinatra22Activity.onActivityResult(Sinatra22Activity.java:158)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.Activity.dispatchActivityResult(Activity.java:5322)
05-23 10:12:50.494: E/AndroidRuntime(1376): at android.app.ActivityThread.deliverResults(ActivityThread.java:3363)
05-23 10:12:50.494: E/AndroidRuntime(1376): ... 11 more

--------------------编辑2-------------------- -

这个 fragment

           String newPath=getRealPathFromURI(getApplicationContext(), result);


Bitmap bMap= BitmapFactory.decodeFile(newPath);
Bitmap out = Bitmap.createScaledBitmap(bMap, 150, 150, false);
File resizedFile = new File(imageStorageDir, "resize.png");

OutputStream fOut=null;
try {
fOut = new BufferedOutputStream(new FileOutputStream(resizedFile));
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
bMap.recycle();
out.recycle();

} catch (Exception e) { // TODO

}
this.mUploadMessage.onReceiveValue(Uri.fromFile(resizedFile));
this.mUploadMessage = null;

打电话

public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

当用户从图库中选择照片时有效,并在从相机拍摄照片时崩溃。我需要结合它们的方法

最佳答案

它所需要的只是一个 if 语句来检查用户选择了什么方法。文件是在 showAttachmentDialog 中创建的,因此私有(private) imageUri 始终具有该文件的 Uri。当用户选择相机选项时,结果也具有该值,而当他选择图库时,结果具有从图库中选择的图像的 Uri

if(result==this.imageUri){
newPath=file.getAbsolutePath();}
else{
newPath=getRealPathFromURI(getApplicationContext(), result);}

最终代码为

@Override
//Receives the results of startActivityFromResult
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
String newPath;
if (requestCode == FILECHOOSER_RESULTCODE) {

if (null == this.mUploadMessage) {
return;
}

Uri result;
if (resultCode != RESULT_OK) {
result = null;
} else {
result = intent == null ? this.imageUri : intent.getData(); // retrieve from the private variable if the intent is null
Log.e("result",result.toString() );
Log.e("intent",this.imageUri.toString() );

}

if(result==this.imageUri){
newPath=file.getAbsolutePath();}
else{
newPath=getRealPathFromURI(getApplicationContext(), result);}

Bitmap bMap= BitmapFactory.decodeFile(newPath);
Bitmap out = Bitmap.createScaledBitmap(bMap, 150, 150, false);
File resizedFile = new File(imageStorageDir, "resize.png");

OutputStream fOut=null;
try {
fOut = new BufferedOutputStream(new FileOutputStream(resizedFile));
out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
bMap.recycle();
out.recycle();

} catch (Exception e) { // TODO

}


this.mUploadMessage.onReceiveValue(Uri.fromFile(resizedFile));
this.mUploadMessage = null;
//resizedFile.delete();


}
}

public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}

关于android - 在上传之前调整从画廊或相机拍摄的图像的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23813604/

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