调整图像正在上传之前,从画廊或相机拍摄, [英] Resize image taken from gallery or camera, before being uploaded

查看:341
本文介绍了调整图像正在上传之前,从画廊或相机拍摄,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上的表单,允许用户上传照片。我的Andr​​oid应用程序使用的WebView以允许用户访问该网站。上传按钮的点击应用程序允许用户选择之间的图像库中的已有或采取新的照片并上传图片。我已经使用这个的code是

I have a form in my site that allows the user to upload a photo. My android app uses WebView to allow users access the site. On click of the upload button the app allows the user to choose between an image already existing in the gallery or take a new photo and upload that image. The code I have used for this is

showAttachmentDialog由openFileChooser称为

showAttachmentDialog is called by the 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

My 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;



        }
    }

我想可以我上传它,我想这是在手机上完成,而不是在网页中前更改图像的大小。我也想从手机中删除调整后的图像时,这样做并保持原型。你可以建议我一个办法做到这一点?我将展示几起案件中那么,我们建议创建位图,并与createScaledBitmap所需的大小调整,但我不知道这是在我的情况下做到这一点的最好办法。这应该在哪里发生?在我的onActivityResult?
在此先感谢!

I would like to be able to change the size of the image before I upload it and I want this to be done on the phone , not in the webpage. I also want to delete the resized image from the phone when this is done and keep the prototype. Could you suggest me a way to do this? I show several cases in SO where it is suggested to create a bitmap and resize it in the desired size with createScaledBitmap but I am not sure which is the best way to do this in my case. Where should this take place? In my onActivityResult? Thanks in advance!

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

--------------------EDIT----------------------

私人文件imageStorageDir,文件;

private File imageStorageDir,file;

我的主要活动宣告这些,在我加入的onActivityResult下面的代码片段

I declared these in my main Activity and added the following snippet in my onActivityResult

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异常

Now the image is being resized and uploaded when taking a photo with the camera but when I am using the gallery I get a 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

----------------------- EDIT2 ----------- ------------ -

-----------------------EDIT2------------------------

这snipet

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

当用户从画廊选择的照片,并采取从相机照片时崩溃工作​​。我需要的方式把它们结合起来。

works when the user chooses photo from gallery and crashes when taking photo from camera. I need the way to combine them

推荐答案

好一切需要的是一个if语句来检查用户选择什么方法。文件在showAttachmentDialog创建并因此私人imageUri八方具有文件的URI。当用户选择摄像机选项结果还具有值,而当他选择像册结果具有从galery选择的图像的URI

Well all it needed was an if statement to check what method the user chose. file is created in the showAttachmentDialog and so the private imageUri allways has the Uri of that file. When the user chooses the camera option result also has that values whereas when he chooses gallery result has the Uri of the image chosen from the galery

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

最后code是

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

这篇关于调整图像正在上传之前,从画廊或相机拍摄,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆