我想只将裁剪后的图像保存到图库中。但它保存了原始的完整图像。如何只保存裁剪的图像?

时间:2013-01-18 06:39:25

标签: android crop

public class ImageCroppMainActivity extends Activity implements OnClickListener{

final int CAMERA_CAPTURE = 1;

//keep track of cropping intent

final int PIC_CROP = 2;

//captured picture uri

private Uri picUri;

final int PICK_IMAGE = 3;   

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_image_cropp_main); 

    //retrieve a reference to the UI button

    Button captureBtn = (Button)findViewById(R.id.capture_btn);

    //handle button clicks

    captureBtn.setOnClickListener(this);

    Button browseBtn = (Button)findViewById(R.id.browse_btn);

    //handle button clicks

    browseBtn.setOnClickListener(this);

}



public void onClick(View v) {

    if (v.getId() == R.id.capture_btn) {   

        try {

            //use standard intent to capture an image

            Intent captureIntent = new 
Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            //we will handle the returned data in onActivityResult

startActivityForResult(captureIntent, CAMERA_CAPTURE);

}

catch(ActivityNotFoundException anfe){

//display an error message

String errorMessage = "Whoops - your device doesn't support capturing images!";

Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);

toast.show();

}  

}

else if(v.getId() == R.id.browse_btn)

{

//use standard intent to capture an image

Intent intent = new Intent(Intent.ACTION_PICK, 

android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

//we will handle the returned data in onActivityResult

startActivityForResult(intent, PICK_IMAGE);

}

}

/**

 * Handle user returning from both capturing and cropping the image

 */

protected void onActivityResult(int requestCode, int resultCode, Intent 

data) {

    if (resultCode == RESULT_OK) {

        //user is returning from capturing an image using the camera

        if(requestCode == CAMERA_CAPTURE){

            //get the Uri for the captured image

            picUri = data.getData();

            //carry out the crop operation

            performCrop();

        }

        //user is returning from cropping the image

        else if(requestCode == PIC_CROP){

            //get the returned data

            Bundle extras = data.getExtras();

            //get the cropped bitmap

            Bitmap thePic = extras.getParcelable("data");

            //retrieve a reference to the ImageView

            ImageView picView = 

 (ImageView)findViewById(R.id.picture);

            //display the returned cropped image
            MediaStore.Images.Media.insertImage(getContentResolver(), thePic, "" , "");

            picView.setImageBitmap(thePic);

        }

        else if(requestCode == PICK_IMAGE)

        {

 picUri = data.getData();

            //carry out the crop operation

            performCrop();

        }}}

   /**

 * Helper method to carry out crop operation

 */

  private void performCrop(){

    //take care of exceptions

    try {

 //call the standard crop action intent (the user device may not support it)

        Intent cropIntent = new 

   Intent("com.android.camera.action.CROP"); 

   //indicate image type and Uri

        cropIntent.setDataAndType(picUri, "image/*");

        //set crop properties

        cropIntent.putExtra("crop", "false");

        //indicate aspect of desired crop

        cropIntent.putExtra("aspectX", 1);

        cropIntent.putExtra("aspectY", 1);

        //indicate output X and Y

        cropIntent.putExtra("outputX", 256);

        cropIntent.putExtra("outputY", 256);

        //retrieve data on return

        cropIntent.putExtra("return-data", true);

        //start the activity - we handle returning in onActivityResult

        startActivityForResult(cropIntent, PIC_CROP);  

     }

    //respond to users whose devices do not support the crop action

    catch(ActivityNotFoundException anfe){

        //display an error message

        String errorMessage = "Whoops - your device doesn't support the

   crop action!";

        Toast toast = Toast.makeText(this, errorMessage, 

   Toast.LENGTH_SHORT);

        toast.show();

    }

   }

  }

4 个答案:

答案 0 :(得分:1)

只需3个步骤即可完成 -

1)Android清单文件

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

<uses-sdk android:minSdkVersion="8" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".SimpleCameraGalleryDemo"
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>

2)SimpleCameraGalleryDemo代码

package camera.test.demo;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class SimpleCameraGalleryDemo extends Activity {
private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_GALLERY = 2;
ImageView imgview;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

imgview = (ImageView) findViewById(R.id.imageView1);
Button buttonCamera = (Button) findViewById(R.id.btn_take_camera);`enter code here`
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
buttonCamera.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
// call android default camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

intent.putExtra(MediaStore.EXTRA_OUTPUT,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString());
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);

try {

intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);

} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 150);

try {

intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_GALLERY);

} catch (ActivityNotFoundException e) {
// Do nothing for now
}
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

if (requestCode == PICK_FROM_CAMERA) {
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
imgview.setImageBitmap(photo);

}
}

if (requestCode == PICK_FROM_GALLERY) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap photo = extras2.getParcelable("data");
imgview.setImageBitmap(photo);

}
}
}
}

3)main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:id="@+id/textViewAddCard"
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Take Image"
android:textSize="16dp"
android:layout_gravity="center"
android:gravity="center"
android:typeface="sans"/>

<Button
android:id="@+id/btn_take_camera"
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Take From Camera"
android:layout_marginTop="5dp"
android:layout_gravity="center"
android:typeface="sans"/>

<Button
android:id="@+id/btn_select_gallery"
android:layout_width="250dp"
android:layout_height="50dp"
android:text="Select from Gallery"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:typeface="sans" />
<ImageView
android:id="@+id/imageView1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

我希望它对您有所帮助。

答案 1 :(得分:0)

请检查以下链接,它将帮助您裁剪图像。

https://github.com/lorensiuswlt/AndroidImageCrop

我认为它会对你有所帮助。让我知道你的状态。

答案 2 :(得分:0)

尝试将此添加到OnActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent 
data) {
if (resultCode == RESULT_OK) {

if(requestCode == CAMERA_CAPTURE){

picUri = data.getData();

performCrop();
} 
else if(requestCode == PIC_CROP){

Bundle extras = data.getExtras();

Bitmap thePic = extras.getParcelable("data");

ImageView picView = (ImageView)findViewById(R.id.picture);

picView.setImageBitmap(thePic);

OutputStream output;
// Find the SD Card path
File filepath = Environment.getExternalStorageDirectory();

// Create a new folder in SD Card
File dir = new File(filepath.getAbsolutePath()
+ "/CroppedImage/");
dir.mkdirs();

// Create a name for the saved image
File file = new File(dir, "crop.jpg" );

try {

output = new FileOutputStream(file);

// Compress into png format image from 0% - 100%
thePic.compress(Bitmap.CompressFormat.JPEG, 100, output);
output.flush();
output.close();

}

catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}

答案 3 :(得分:0)

HI please try this to save to your gallery
MainActivity:
-----------------

package com.example.satis.crop;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    Button buttonCamera, buttonGallery ;
    File file;
    Uri uri;
    Intent CamIntent, GalIntent, CropIntent ;
    public  static final int RequestPermissionCode  = 1 ;
    DisplayMetrics displayMetrics ;
    int width, height;

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

        imageView = (ImageView)findViewById(R.id.imageview);
        buttonCamera = (Button)findViewById(R.id.button2);
        buttonGallery = (Button)findViewById(R.id.button1);

        EnableRuntimePermission();

        buttonCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ClickImageFromCamera() ;

            }
        });

        buttonGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                GetImageFromGallery();

            }
        });

    }

    public void ClickImageFromCamera() {

        CamIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

        file = new File(Environment.getExternalStorageDirectory(),
                "file" + String.valueOf(System.currentTimeMillis()) + ".jpg");
        uri = Uri.fromFile(file);

        CamIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri);

        CamIntent.putExtra("return-data", true);

        startActivityForResult(CamIntent, 0);

    }

    public void GetImageFromGallery(){

        GalIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(Intent.createChooser(GalIntent, "Select Image From Gallery"), 2);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0 && resultCode == RESULT_OK) {

            ImageCropFunction();

        }
        else if (requestCode == 2) {

            if (data != null) {

                uri = data.getData();

                ImageCropFunction();

            }
        }
        else if (requestCode == 1) {

            if (data != null) {

                Bundle bundle = data.getExtras();

                Bitmap bitmap = bundle.getParcelable("data");

                imageView.setImageBitmap(bitmap);
                MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "cropped" , "cropped");


            }
        }
    }

    public void ImageCropFunction() {

        // Image Crop Code
        try {
            CropIntent = new Intent("com.android.camera.action.CROP");

            CropIntent.setDataAndType(uri, "image/*");

            CropIntent.putExtra("crop", "true");
            CropIntent.putExtra("outputX", 180);
            CropIntent.putExtra("outputY", 180);
            CropIntent.putExtra("aspectX", 3);
            CropIntent.putExtra("aspectY", 4);
            CropIntent.putExtra("scaleUpIfNeeded", true);
            CropIntent.putExtra("return-data", true);

            startActivityForResult(CropIntent, 1);

        } catch (ActivityNotFoundException e) {

        }
    }
    //Image Crop Code End Here

    public void EnableRuntimePermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                Manifest.permission.CAMERA))
        {

            Toast.makeText(MainActivity.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                    Manifest.permission.CAMERA}, RequestPermissionCode);

        }
    }

    @Override
    public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {

        switch (RC) {

            case RequestPermissionCode:

                if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {

                    Toast.makeText(MainActivity.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();

                } else {

                    Toast.makeText(MainActivity.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();

                }
                break;
        }
    }

}


AndroidManifest.xml
-----------------------

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

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-feature android:name="android.hardware.camera" />

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

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

</manifest>


Activity_main:
-------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFECB3"
    tools:context="com.example.satis.crop.MainActivity">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="325dp"
        android:id="@+id/imageview"
        android:layout_centerHorizontal="true"
        />

    <Button
        android:text="Click Here For PICK image from Gallery TO CROP"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageview"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="7dp"
        android:id="@+id/button1" />

    <Button
        android:text="Click Here For CLICK image from Camera TO CROP"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_alignRight="@+id/button1"
        android:layout_alignEnd="@+id/button1"
        android:layout_marginTop="7dp"
        android:id="@+id/button2" />
</RelativeLayout>

res/xml:
--------
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="." />
</paths>