【问题标题】:How to pick an image from gallery,crop and save that in data partition如何从图库中选择图像,裁剪并将其保存在数据分区中
【发布时间】:2014-01-31 00:47:57
【问题描述】:

我需要一些帮助 我想从图库中选择一个图像,然后将其重新调整为自定义大小,例如 480*800,然后将其放入数据分区的文件夹中(例如(/data/test_wall))。 我多次尝试谷歌搜索,但没有注意到。

到目前为止,这是我的代码,但我无法从图库中选择并保存图像给我强制关闭:

package com.example.walpaperpicker;

import java.io.FileOutputStream;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {

private static final int PICK_FRPM_GALLERY = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button1  = (Button) findViewById(R.id.button1);

    button1.setOnClickListener(new View.OnClickListener() { 
        @Override
        public void onClick(View v) {
            PickPic();
        }

        private void PickPic() {
            // this code working for pick a picture with camera
             Intent cameraIntent = new Intent(
                    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, PICK_FRPM_GALLERY);

            // this code not working give me fc after i select picture from gallery see my logcat
            /*Intent GallaryIntent = new Intent();
            GallaryIntent.setType("image/*");
            GallaryIntent.setAction(Intent.ACTION_GET_CONTENT);

            startActivityForResult(GallaryIntent, PICK_FRPM_GALLERY);*/


        }
    });
}
@SuppressLint("SdCardPath")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_FRPM_GALLERY) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                ImageView test = (ImageView) findViewById(R.id.imageView1);
                test.setImageBitmap(photo);
                try {
                    //I want put it in data partition but i dont know this is for sdcard
                    FileOutputStream out = new FileOutputStream("/sdcard/wallpaper.png");
                    photo.compress(Bitmap.CompressFormat.PNG, 90, out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

/*i want crop output picture
 *to custom size for example 480*800
 *but i dont know.
 */
  }

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.walpaperpicker"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />
    <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE"> </uses-permission>
    <uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"> </uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.walpaperpicker.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

如果我从相机拍摄照片并将其保存在“/sdcard/wallpaper.png”中,此代码将起作用 但我不想从相机中挑选一张照片并将其放入“sdcard”中。 我想先从图库中挑选一张图片,将其裁剪为 480*800 然后把它放在数据分区的文件夹中(我有根设备)。见我上面的代码。

这是我的日志猫

01-31 02:27:37.545: E/AndroidRuntime(5241): FATAL EXCEPTION: main
01-31 02:27:37.545: E/AndroidRuntime(5241): Process: com.example.walpaperpicker, PID: 5241
01-31 02:27:37.545: E/AndroidRuntime(5241): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:26274 flg=0x1 }} to activity {com.example.walpaperpicker/com.example.walpaperpicker.MainActivity}: java.lang.NullPointerException
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3368)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3411)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.ActivityThread.access$1300(ActivityThread.java:138)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.os.Looper.loop(Looper.java:136)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.ActivityThread.main(ActivityThread.java:5050)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at java.lang.reflect.Method.invokeNative(Native Method)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at java.lang.reflect.Method.invoke(Method.java:515)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at dalvik.system.NativeStart.main(Native Method)
01-31 02:27:37.545: E/AndroidRuntime(5241): Caused by: java.lang.NullPointerException
01-31 02:27:37.545: E/AndroidRuntime(5241):     at com.example.walpaperpicker.MainActivity.onActivityResult(MainActivity.java:50)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.Activity.dispatchActivityResult(Activity.java:5433)
01-31 02:27:37.545: E/AndroidRuntime(5241):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3364)
01-31 02:27:37.545: E/AndroidRuntime(5241):     ... 11 more

感谢您的帮助 我在等。

【问题讨论】:

    标签: java android android-intent bitmap gallery


    【解决方案1】:

    我已经写了几篇关于如何选择图库图像或缩略图的文章,对你有帮助

    How to Pick Image from Gallery in Android

    How to pick the Image thumb-nail from gallery in android

    好的,让我试着解释一下它是如何工作的

    1.我们需要创建一个从图库中挑选图片的意图

    Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore  
                                  .Images.Media.EXTERNAL_CONTENT_URI);  
    startActivityForResult(i, RESULT_LOAD_IMAGE); 
    

    2。在同一个活动中,我们需要在 onActivityResult 方法中处理拾取的图像

    @Override  
        protected void onActivityResult(int requestCode,   
                                         int resultCode, Intent data) {  
            super.onActivityResult(requestCode, resultCode, data);  
    
            if (requestCode == RESULT_LOAD_IMAGE &&   
                                  resultCode == RESULT_OK && null != data) {  
                Uri selectedImage = data.getData();  
                String[] filePathColumn = { MediaStore.Images.Media.DATA };  
    
                Cursor cursor = getContentResolver().query(selectedImage,  
                        filePathColumn, null, null, null);  
                cursor.moveToFirst();  
    
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);  
                String picturePath = cursor.getString(columnIndex);  
                cursor.close(); 
    
                imageView = (ImageView) findViewById(R.id.imageView);
    
                //here you can call createImageThumbnail method passing (picturePath,480,800) 
                //and set the received bitmap imageview directly instead of storing in bitmap.
                // eg. imageView.setImageBitmap(createImageThumbnail( picturePath, 480, 800));
    
    
                imageView.setImageBitmap(BitmapFactory  
                                .decodeFile(picturePath));  
    
            }  
    
    
        }  
    

    3.根据需要调整图像大小(宽度 * 高度)

    Bitmap createImageThumbnail(String imagePath, int width, int height) {  
      BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();  
      bmpFactoryOptions.inJustDecodeBounds = true;  
      int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight  
        / (float) height);  
      int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth  
        / (float) width);  
    
      if (heightRatio > 1 || widthRatio > 1) {  
       if (heightRatio > widthRatio) {  
        bmpFactoryOptions.inSampleSize = heightRatio;  
       } else {  
        bmpFactoryOptions.inSampleSize = widthRatio;  
       }  
      }  
      bmpFactoryOptions.inJustDecodeBounds = false;  
    
      if (bitmap != null) {  
       bitmap.recycle();  
       bitmap = null;  
      }  
    
      bitmap = BitmapFactory.decodeFile(imagePath, bmpFactoryOptions);  
      return bitmap;  
     } 
    

    如果您在这方面有任何问题,请告诉我。乐于提供帮助。

    【讨论】:

    • 谢谢哥们,我试过你的代码,但我在重新大小方面有问题,我想你忘了我想把图片放在数据分区的文件夹中 // imageView.setImageBitmap(createImageThumbnail( picturePath, 480, 800));bmpFactoryOptions.inJustDecodeBounds = false; if (bitmap != null) { bitmap.recycle(); bitmap = null; } bitmap = BitmapFactory.decodeFile(imagePath, bmpFactoryOptions); return bitmap; //i have errors with bitmap and imagePath(this is not should be "picturePath"??) cant in lines above let me to compile }
    猜你喜欢
    • 1970-01-01
    • 2015-10-23
    • 1970-01-01
    • 2020-12-21
    • 2018-01-17
    • 2019-05-18
    • 2017-03-15
    • 2016-07-22
    • 2018-10-24
    相关资源
    最近更新 更多