First, the realization of taking pictures, select pictures and crop picture effects
According to the style of the previous blog, first look at the implementation effect.
II. Application of Ucrop project
Think of the previous yalantis/ucrop effect is more gorgeous, but after the study of the source found in the custom interface is still a bit of restrictions, so on its basis to do the modification Android-crop, the custom interface independent out, let the user set free. The following image selects the image and trims the demo using the Android-crop implementation of the Imitation micro-letter.
Third, the realization of ideas
Relatively simple to select the device picture cropping, and save the cropped picture to the specified path;
Call the system to take photos, save the picture on the SD card, and then crop the picture and save the cropped picture in the specified path.
Process the figure looks like this:
Four, the selection box implementation
This is done through Popupwindow, and of course it can be implemented in other ways according to requirements. The implementation effect is shown in the following illustration:
1. XML layout
<? xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android: layout_width = "fill_parent"
android: layout_height = "wrap_content"
android: gravity = "center_horizontal"
android: orientation = "vertical">
<LinearLayout
android: id = "@ + id / pop_layout"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_alignParentBottom = "true"
android: background = "# 444"
android: gravity = "center_horizontal"
android: orientation = "vertical">
<Button
android: id = "@ + id / picture_selector_take_photo_btn"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_marginLeft = "10dip"
android: layout_marginRight = "10dip"
android: layout_marginTop = "10dp"
android: background = "# 4d69ff"
android: padding = "10dp"
android: text = "take picture"
android: textColor = "# CEC9E7"
android: textSize = "18sp"
android: textStyle = "bold" />
<Button
android: id = "@ + id / picture_selector_pick_picture_btn"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_marginLeft = "10dip"
android: layout_marginRight = "10dip"
android: layout_marginTop = "5dp"
android: background = "# 4d69ff"
android: padding = "10dp"
android: text = "Select from album"
android: textColor = "# CEC9E7"
android: textSize = "18sp"
android: textStyle = "bold" />
<Button
android: id = "@ + id / picture_selector_cancel_btn"
android: layout_width = "match_parent"
android: layout_height = "wrap_content"
android: layout_marginBottom = "15dip"
android: layout_marginLeft = "10dip"
android: layout_marginRight = "10dip"
android: layout_marginTop = "20dp"
android: background = "@ android: color / white"
android: padding = "10dp"
android: text = "Cancel"
android: textColor = "# 373447"
android: textSize = "18sp"
android: textStyle = "bold" />
</ LinearLayout>
</ RelativeLayout>
2. Code writing
Public Selectpicturepopupwindow {
super (context);
Layoutinflater Inflater = (layoutinflater) context.getsystemservice (context.layout_inflater_service);
Mmenuview = inflater.inflate (r.layout.layout_picture_selector, null);
TAKEPHOTOBTN = (Button) Mmenuview.findviewbyid (R.ID.PICTURE_SELECTOR_TAKE_PHOTO_BTN);
PICKPICTUREBTN = (Button) Mmenuview.findviewbyid (R.ID.PICTURE_SELECTOR_PICK_PICTURE_BTN);
CANCELBTN = (Button) Mmenuview.findviewbyid (R.ID.PICTURE_SELECTOR_CANCEL_BTN);
Set button to listen for
takephotobtn.setonclicklistener (this);
Pickpicturebtn.setonclicklistener (this);
Cancelbtn.setonclicklistener (this);
Set the button to monitor when creating the Selectpicturepopupwindow. Here, write a selection listener interface:
/**
* Select Listener interface
/public interface Onselectedlistener {
void onselected (View v, int position);
The callback parameter is the click of the button view and the index of the current button, so as long as the choice of listening to return the interface of the callback.
@Override public
void OnClick (View v) {
switch (V.getid ()) {Case
r.id.picture_selector_take_photo_btn:
if (null!= monselectedlistener) {
monselectedlistener.onselected (V, 0);
}
break;
Case R.ID.PICTURE_SELECTOR_PICK_PICTURE_BTN:
if (null!= monselectedlistener) {
Monselectedlistener.onselected (v, 1);
}
break;
Case R.ID.PICTURE_SELECTOR_CANCEL_BTN:
if (null!= monselectedlistener) {
monselectedlistener.onselected ( V, 2);
}
break;
}
}
Popupwindow initialization, monitoring settings, as long as the display and hide two methods can be provided.
/**
* Adds a view control to the Popupwindow and displays
*
@param activity/public
void Showpopupwindow (activity Activity) {
Popupwindow = new Popupwindow (Mmenuview,//Add to Popupwindow
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
Popupwindow.setbackgrounddrawable (New colordrawable (color.transparent));
Popupwindow.showatlocation (Activity.getwindow () Getdecorview (), Gravity.center | Gravity.bottom, 0, 0);
Popupwindow.setanimationstyle (Android. R.style.animation_inputmethod); Sets the animation effect
Popupwindow.setfocusable (False) displayed by the window;//click anywhere else to hide the keyboard Popupwindow
popupwindow.update ();
}
/**
* Remove Popupwindow
/public
void Dismisspopupwindow () {
if (Popupwindow!= null && Popupwindow.isshowing ()) {
Popupwindow.dismiss ();
Popupwindow = null;
}
OK, the implementation of the selection box here is complete.
V. Use the selection box
Through our face selection box package, it is simpler to use, only need to initialize and set the selection of listening to it.
1. Initialize the selection box
Mselectpicturepopupwindow = new Selectpicturepopupwindow (mcontext);
Mselectpicturepopupwindow.setonselectedlistener (this);
2. Set the selection box listening
@Override public
void Onselected (View v., int position) {
switch (position) {case
0:
//TODO: "Photo" button clicked The break
;
Case 1:
//TODO: "Select from album" button was clicked the break
;
Case 2:
//TODO: "Cancel" button was clicked on Break
;
}
And then on the fragment on the package, we named Pictureselectfragment.
Vi. take photos and save pictures
Call the system's camera and save the captured picture to the specified location.
@Override public
void Onselected (View v., int position) {
switch (position) {case
0:
//the "Photo" button was clicked
Mselectpicturepopupwindow.dismisspopupwindow ();
Intent takeintent = new Intent (mediastore.action_image_capture);
The following sentence specifies the path
takeintent.putextra (Mediastore.extra_output, Uri.fromfile (New File (Mtempphotopath)) for the photo store after the camera is taken. ;
Startactivityforresult (Takeintent, camera_request_code);
break;
Case 1:
//TODO: "Select from album" button was clicked the break
;
Case 2:
//TODO: "Cancel" button was clicked on Break
;
}
The designated location here is the SD card in this directory
Mtempphotopath = environment.getexternalstoragedirectory () + File.separator + "photo.jpeg";
When the photo is finished, it will be recalled to Onactivityresult, and we will be able to deal with the clipping of the picture here.
@Override public
void Onactivityresult (int requestcode, int resultcode, Intent data) {
if (ResultCode = = Mactivit Y.RESULT_OK) {
switch (requestcode) {case
Camera_request_code:
//TODO: Call camera to take photo break
;
}
Super.onactivityresult (Requestcode, ResultCode, data);
}
Vii. Photo Album Selection
Call the system's selection picture
@Override public
void Onselected (View v., int position) {
switch (position) {case
0:
//the "Photo" button was clicked
Mselectpicturepopupwindow.dismisspopupwindow ();
Intent takeintent = new Intent (mediastore.action_image_capture);
The following sentence specifies the path
takeintent.putextra (Mediastore.extra_output, Uri.fromfile (New File (Mtempphotopath)) for the photo store after the camera is taken. ;
Startactivityforresult (Takeintent, camera_request_code);
break;
Case 1:
//"Select from Album" button was clicked on
Mselectpicturepopupwindow.dismisspopupwindow ();
Intent pickintent = new Intent (Intent.action_pick, null);
If you limit the type of picture uploaded to the server, you can write directly such as: "Image/jpeg, Image/png type"
pickintent.setdataandtype ( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
Startactivityforresult (Pickintent, gallery_request_code);
break;
Case 2:
//TODO: "Cancel" button was clicked on Break
;
}
When the shot selection picture is completed, it is recalled to Onactivityresult, where the selected return result is processed.
@Override public
void Onactivityresult (int requestcode, int resultcode, Intent data) {
if (ResultCode = = Mactivit Y.RESULT_OK) {
switch (requestcode) {case
Camera_request_code:
//TODO: Call camera to take photo break
;
Case Gallery_request_code:
//TODO: Get break from album directly
;
}
Super.onactivityresult (Requestcode, ResultCode, data);
}
Eight, use crop to crop the picture
Crop the picture, here set the width-height ratio of 1:1, the maximum size of 512*512, of course, according to their own needs to set.
/**
* Crop image method Implementation
* *
@param uri/public
void startcropactivity (Uri uri) {
ucrop.of uri, Mdestinationuri)
. Withaspectratio (1, 1). Withmaxresultsize (a).
Withtargetactivity ( Cropactivity.class)
. Start (mactivity, this);
}
When the cropactiivty is finished, it is recalled to Onactivityresult, where the returned results of the selection are processed.
@Override public
void Onactivityresult (int requestcode, int resultcode, Intent data) {
if (ResultCode = = Mactivit Y.RESULT_OK) {
switch (requestcode) {case
Camera_request_code://Call camera photo
File temp = new file ( Mtempphotopath);
Startcropactivity (Uri.fromfile (temp));
break;
Case Gallery_request_code://directly from the album to obtain
startcropactivity (Data.getdata ());
break;
Case Ucrop.request_crop:
//TODO: Crop the picture result break
;
Case UCROP.RESULT_ERROR:
//TODO: Crop picture error break
;
}
Super.onactivityresult (Requestcode, ResultCode, data);
}
The Cropactivity interface looks like this:
Of course, you can easily design the following two pictures:
1. XML layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="true"
android:fitsSystemWindows="true">
<include layout="@layout/toolbar_layout" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toolbar"
android:background="#000">
<com.kevin.crop.view.UCropView
android:id="@+id/weixin_act_ucrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible" />
</FrameLayout>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.FloatingActionButton
android:id="@+id/crop_act_save_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="@dimen/fab_margin"
android:src="@mipmap/ic_done_white"
fab:fabSize="normal" />
</android.support.design.widget.CoordinatorLayout>
</RelativeLayout>
Can be found very simple, there is only one major Cropview, and that is what the Ucrop framework provides for us.
2. Code writing
@Override
protected void Initviews () {
inittoolbar ();
Mgesturecropimageview = Mucropview.getcropimageview ();
Moverlayview = Mucropview.getoverlayview ();
Set Allow scaling
mgesturecropimageview.setscaleenabled (true);
Sets the prohibit rotation
mgesturecropimageview.setrotateenabled (false);
Sets the external shadow color
Moverlayview.setdimmedcolor (Color.parsecolor ("#AA000000"));
Sets whether the surrounding shadow is an ellipse (if False is a rectangle)
Moverlayview.setovaldimmedlayer (false);
Sets the display clipping border
moverlayview.setshowcropframe (true);
Setting does not show cropping grid
Moverlayview.setshowcropgrid (false);
Final Intent Intent = Getintent ();
Setimagedata (intent);
}
private void Setimagedata (Intent Intent) {Uri Inputuri = Intent.getparcelableextra (Ucrop.extra_input_uri);
Moutputuri = Intent.getparcelableextra (Ucrop.extra_output_uri);
if (Inputuri!= null && moutputuri!= null) {try {Mgesturecropimageview.setimageuri (Inputuri);
catch (Exception e) {setresultexception (e);
Finish ();
} else {setresultexception (new NullPointerException ("Both input and output Uri must be specified"));
Finish (); //Set crop width ratio if (Intent.getbooleanextra (Ucrop.extra_aspect_ratio_set, False)) {Float Aspectratiox = Intent.getflo
Atextra (ucrop.extra_aspect_ratio_x, 0);
float Aspectratioy = Intent.getfloatextra (ucrop.extra_aspect_ratio_y, 0); if (Aspectratiox > 0 && aspectratioy > 0) {mgesturecropimageview.settargetaspectratio (Aspectratiox/aspe
Ctratioy);
else {mgesturecropimageview.settargetaspectratio (cropimageview.source_image_aspect_ratio); }//Set maximum width of clipping if (Intent.getbooleanexTra (Ucrop.extra_max_size_set, false)) {int Maxsizex = Intent.getintextra (ucrop.extra_max_size_x, 0);
int Maxsizey = Intent.getintextra (ucrop.extra_max_size_y, 0);
if (Maxsizex > 0 && maxsizey > 0) {mgesturecropimageview.setmaxresultimagesizex (Maxsizex);
Mgesturecropimageview.setmaxresultimagesizey (Maxsizey);
else {LOG.W (TAG, "extra_max_size_x and extra_max_size_y must be greater than 0");
}
}
}
Above for Cropview configuration, more configuration please refer to the project source code.
Most importantly, crop the save Picture:
private void Cropandsaveimage () {
outputstream outputstream = null;
try {
final Bitmap croppedbitmap = Mgesturecropimageview.cropimage ();
if (Croppedbitmap!= null) {
outputstream = Getcontentresolver (). Openoutputstream (Moutputuri);
Croppedbitmap.compress (Bitmap.CompressFormat.JPEG, outputstream);
Croppedbitmap.recycle ();
Setresulturi (Moutputuri, Mgesturecropimageview.gettargetaspectratio ());
Finish ();
} else {
setresultexception (new NullPointerException ("Cropimageview.cropimage () returned null."));
}
catch (Exception e) {
setresultexception (e);
Finish ();
} finally {
bitmaploadutils.close (outputstream);
}
}
Pictureselectfragment a successful return value for the cropping process
/**
* Processing a successful return value * * @param result *
/private void Handlecropresult (Intent result) {
Deletetempphotofile ();
Final Uri Resulturi = ucrop.getoutput (result);
if (null!= resulturi && null!= monpictureselectedlistener) {
Bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap (Mactivity.getcontentresolver (), Resulturi);
} catch ( FileNotFoundException e) {
e.printstacktrace ();
} catch (IOException e) {
e.printstacktrace ();
}
monpictureselectedlistener.onpictureselected (Resulturi, bitmap);
} else {
Toast.maketext (mcontext, "Cannot cut selection picture", Toast.length_short). Show ();
}
Handling the return value of a cropping failure
/**
* Processing the return value of the clipping failure
* *
@param result
/private void Handlecroperror (Intent result) {
Deletetempphotofile ();
Final Throwable croperror = ucrop.geterror (result);
if (croperror!= null) {
LOG.E (TAG, "Handlecroperror:", croperror);
Toast.maketext (Mcontext, Croperror.getmessage (), Toast.length_long). Show ();
else {
Toast.maketext (mcontext, "Cannot cut selection picture", Toast.length_short). Show ();
}
The selected callback interface is set up here to facilitate encapsulation and extraction.
/**
* Image selected Callback interface/
public
interface Onpictureselectedlistener {
/**
* Image selected Listener Callback
*
* @param fileuri
* @param bitmap
/void onpictureselected (Uri Fileuri, bitmap bitmap);
After five or six or seven steps, our pictureselectfragment is done, in the use of the time as long as inherited it, a few lines of code is done.
Ix. Use of Pictureselectfragment
Set up the picture click
Mpictureiv.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick ( View v) {
selectpicture ();
}
});
Set crop picture result listener
Setonpictureselectedlistener (new Onpictureselectedlistener () {
@Override public
Void Onpictureselected (Uri Fileuri, Bitmap Bitmap) {
mpictureiv.setimagebitmap (Bitmap);
String FilePath = Fileuri.getencodedpath ();
String ImagePath = Uri.decode (FilePath);
Toast.maketext (Mcontext, "The picture has been saved to:" + ImagePath, Toast.length_long). Show ();
}
OK, after our package and base class extraction, it is very simple to use.
Ten, download
source code and examples
Android-crop Libraries to use
For more information, you can refer to the topic "Android image Processing" to learn.
This is the entire content of this article, I hope to learn more about Android software programming help.