Wednesday, September 14, 2016

Image Cropping in Android

Image Cropping without Library


Here I have implemented image cropping without any third party library.



First of all we have to add permission on Manifest.xml like below.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and add the below code in activity_main.xml.

<?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"
tools:context="fresco_cache_testing.com.imagecropingdemo.MainActivity">

<Button
android:id="@+id/btnCrop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Crop"
android:textAllCaps="false"
/>

<ImageView
android:id="@+id/result_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/btnCrop"
/>

</RelativeLayout>



and here is MainActivity.java code.

public class MainActivity extends AppCompatActivity {

private ImageView resultView;
private Button btnCrop;
private Uri UriProfilePic;
private Integer PHOTO_PICK = 1,PHOTO_CLICK = 2;
private File filepath, cropfilepath;
private final int PIC_CROP = 3;

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

btnCrop= (Button) findViewById(R.id.btnCrop);
resultView = (ImageView) findViewById(R.id.result_image);

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

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

UriProfilePic = Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "myFile.jpg"));
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
if (android.os.Build.VERSION.SDK_INT > 10) {
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
}
startActivityForResult(intent, PHOTO_PICK);
}
});
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == PHOTO_PICK) {
UriProfilePic = data.getData();
if (UriProfilePic.toString().contains("content://com.google.android.apps.photos.content/0/")) {
filepath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/sent_" + System.currentTimeMillis() + ".png");
} else if (UriProfilePic.toString().contains("content://com.google.android.apps.photos.content/1/")) {
filepath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/sent_" + System.currentTimeMillis() + ".mp4");
}
if (filepath != null) {
UriProfilePic = getImageContentUri(MainActivity.this, filepath);
if(UriProfilePic!=null) {
performCrop(UriProfilePic);
} else {
Toast.makeText(MainActivity.this,"Please Select correct image",Toast.LENGTH_LONG).show();
}
} else {
// Log.e("path", "" + filePath);
if(UriProfilePic!=null) {
performCrop(UriProfilePic);
} else {
Toast.makeText(MainActivity.this,"Please Select correct image",Toast.LENGTH_LONG).show();
}
}
} else if (resultCode == RESULT_OK && requestCode == PHOTO_CLICK) {
if(UriProfilePic!=null) {
performCrop(UriProfilePic);
}
} else if (requestCode == PIC_CROP && resultCode == RESULT_OK) {
Log.e("Photo croping....","-======>");
try {
if(data != null)
{
Bitmap thePic = getBitmapFromFile(cropfilepath);
resultView.setImageBitmap(thePic);
}
} catch (Exception e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}


public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}

private void performCrop(Uri UriCamera) {
// 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(UriCamera, "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// 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", false);
cropfilepath = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/sent_"
+ System.currentTimeMillis()
+ ".jpg");

cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropfilepath));
cropIntent.putExtra("output", Uri.fromFile(cropfilepath));
cropIntent.putExtra("return-data", false);
// 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();
}
}

private Bitmap getBitmapFromFile(File photoPath) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
return BitmapFactory.decodeFile(photoPath.getAbsolutePath(), options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}