简体   繁体   中英

How to pick an image from gallery,crop and save that in data partition

i need some help i want pick an image from gallery after that re size it to custom size for example to 480*800 ,then put it in a folder of data partition(for example(/data/test_wall)). i tried Google search many times but noting.

here is my code till now but i cant pick from gallery and save image give me force close:

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>

this code working if i take picture from camera and will save it in "/sdcard/wallpaper.png" but i don't want pick a picture from camera and put it in "sdcard" . i want first pick an image from gallery,crop it to 480*800 then put that in a folder of data partition(i have rooted device) .see my above codes.

here is my log-cat

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

thanks for helping i am waiting .

I have written couple of articles on How to pick Gallery Image or Thumbnail, will help you

How to Pick Image from Gallery in Android

And

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

Okay let me try to explain how it works

1. we need to create an intent for picking image from Gallary

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

2. In the same activity we need to handle picked image in onActivityResult method

@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. resize the Image as you want ( Width * Height )

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

Let me know if you have any trouble in this.Happy to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM