Android clipping Image Implementation Method Example _android

Source: Internet
Author: User
Tags base64 comments

This example describes the implementation of the Android cropping image. Share to everyone for your reference, specific as follows:

Package Com.xiaoma.piccut.demo;
Import Java.io.File;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.graphics.Bitmap;
Import android.graphics.drawable.BitmapDrawable;
Import android.graphics.drawable.Drawable;
Import Android.net.Uri;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.provider.MediaStore;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.ImageButton;
Import Android.widget.ImageView;
/** * @Title: Piccutdemoactivity.java * @Package Com.xiaoma.piccut.demo * @Description: Picture cutting function Test * @author xiaoma * *
  public class Piccutdemoactivity extends activity implements Onclicklistener {private ImageButton IB = null;
  Private ImageView IV = NULL;
  Private Button btn = null;
  Private String TP = NULL; /** called the activity is a. */@Override public void OnCreate(Bundle savedinstancestate)
    {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.main);
  Initialize init ();
    /** * Initialization method implementation/private void Init () {IB = (ImageButton) Findviewbyid (R.id.imagebutton1);
    IV = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);
    BTN = (Button) Findviewbyid (R.id.button1);
    Ib.setonclicklistener (this);
    Iv.setonclicklistener (this);
  Btn.setonclicklistener (this); /** * Control Click event Implementation * Because a friend asked how the background map of different controls to achieve, * I used three controls in this place, just to record my own learning * Everyone thinks it's useless to skip the * * * @Override P
      ublic void OnClick (View v) {switch (V.getid ()) {case R.id.imagebutton1:showpickdialog ();
    Break
      Case R.id.imageview1:showpickdialog ();
    Break
      Case R.id.button1:showpickdialog ();
    Break
    Default:break; }/** * Select Prompt dialog box */private void Showpickdialog () {new Alertdialog.builder (this). Settitle ("Set Avatar ...") ). Setnegativebutton ("album", New DialoginterfAce.
      Onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {Dialog.dismiss ();  /** * Just beginning, I do not know what Action_pick is, and then directly look at the Intent source, * can find a lot of things, Intent is a very powerful thing, we must carefully read under * * * Intent
      Intent = new Intent (Intent.action_pick, NULL);
       /** * The following sentence, written in other ways, is the same effect if: * Intent.setdata (MediaStore.Images.Media.EXTERNAL_CONTENT_URI); * Intent.settype ("image/*"); * Set the data type * If friends want to restrict upload to the server of the type of picture can be directly written as: "Image/jpeg, Image/png and other types" * This place pony has a question, hope Hope Master Answer: Is this data URI and type why should be divided into two forms to write it?
       What's the difference?
      * * Intent.setdataandtype (MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
     Startactivityforresult (Intent, 1); }). Setpositivebutton ("Photographed", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dia
      Log, int whichbutton) {Dialog.dismiss (); /** * The following sentence is still the same as the old, call quick photo function, as for why the quick photo, you can refer to the following official * documents, you_sdk_path/docs/guide/topics/media/camera.html * I just look at the time because too long to seriously look, is actually wrong, this inside useful too much, so we do not think * official documents too long will not look, in fact, is wrong, this place the pony is wrong, must be corrected * *
      Intent Intent = new Intent (mediastore.action_image_capture);
          The following sentence specifies the path Intent.putextra (Mediastore.extra_output, Uri. FromFile (new File) for the photo store after the camera is called (environment
      . getExternalStorageDirectory (), "xiaoma.jpg"));
     Startactivityforresult (Intent, 2);
  ). Show (); 
    @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {switch (Requestcode) {
      If it is directly from the album to obtain Case 1:startphotozoom (Data.getdata ());
    Break 
      If the camera is called the case 2:file temp = new File (environment.getexternalstoragedirectory () + "/xiaoma.jpg");
      Startphotozoom (Uri.fromfile (temp));
    Break Get cropped picture case 3:/** * NOT NULL judge everyone must verify, if not validated, * in the cut if found dissatisfied, to be trimmed, discard * Current function, will be reported nullexcept Ion, pony only * in this place to add, we can according to different circumstances in the appropriate
       * Place to make judgments to handle similar situations */if (data!= null) {Setpictoview (data);
    } break;
    Default:break;
  } super.onactivityresult (Requestcode, ResultCode, data); /** * Crop Picture method implementation * @param URI/public void Startphotozoom (URI uri) {/* * As for the following intent action, how do I know , you can look under their own path under the following page * yourself_sdk_path/docs/reference/android/content/intent.html * directly in the inside Ctrl+f search: crop, before the pony did not carefully read , in fact, Android has already had its own picture cutting function, * is directly tuned to the local library, pony do not know C C + + This does not do a detailed understanding of the wheel, with wheels, no longer study the wheel is how * system to do ...
    Ho ho/Intent Intent = new Intent ("Com.android.camera.action.CROP");
    Intent.setdataandtype (URI, "image/*");
    The following crop=true is set to set the view trimmed Intent.putextra ("crop", "true") displayed in the open intent.
    Aspectx Aspecty is a wide-height proportional Intent.putextra ("Aspectx", 1);
    Intent.putextra ("Aspecty", 1);
    Outputx Outputy is a cropped picture of wide-high Intent.putextra ("Outputx", 150);
    Intent.putextra ("Outputy", 150);
    Intent.putextra ("Return-data", true); StartActivityforresult (Intent, 3); /** * Save cropped picture data * @param picdata/private void Setpictoview (Intent picdata) {Bundle Extras = PICDA
    Ta.getextras ();
      if (extras!= null) {Bitmap photo = extras.getparcelable ("Data");
      drawable drawable = new bitmapdrawable (photo); /** * The following annotation method is to cut the picture to Base64coder character way on the * to the server, QQ Avatar upload method with this similar * * */*bytearrayoutputstream St
      Ream = new Bytearrayoutputstream ();
      Photo.compress (Bitmap.CompressFormat.JPEG, N, Stream);
      Byte[] B = Stream.tobytearray ();
      Store a picture stream as a string tp = new String (Base64coder.encodelines (b)); This place you can write down to the server upload picture implementation, directly to the TP upload can be, server processing method is the server over there, Roar roar if the data of the server to download or in the form of Base64coder, you can use the following ways to convert to us can To use the type of picture just OK ...
      Ho ho Bitmap dbitmap = bitmapfactory.decodefile (TP);
      drawable drawable = new bitmapdrawable (DBITMAP);
      * * Ib.setbackgrounddrawable (drawable);
    Iv.setbackgrounddrawable (drawable);

 }
  }
}

Cut the class used in the next clip, and you'll see the comments in detail:

Package Com.xiaoma.piccut.demo; /** * The following comments are available when downloading this class, would have to delete, but looked down unexpectedly is license, roar, * good things, stay in the comments, ready to use, we need to add license to the following URL to find Oh * * *//EPL, Eclipse Pub Lic License, V1.0 or later, Http://www.eclipse.org/legal//LGPL, GNU Lesser General public License, V2.1 or later, http:// Www.gnu.org/licenses/lgpl.html//GPL, GNU General public License, V2 or later, http://www.gnu.org/licenses/gpl.html//al , Apache License, V2.0 or later, http://www.apache.org/licenses//bsd, BSD License, http://www.opensource.org/licenses/
bsd-license.php/** * A Base64 encoder/decoder.
* * <p> * This class are used to encode and decode data in Base64 format as described in RFC 1521. * <p> * Project Home Page:www.source-code.biz/base64coder/java * Author:christian d ' heureuse, Inventec informati
K AG, Zurich, switzerland<br> * Multi-licensed:epl/lgpl/gpl/al/bsd. * */** * This class is available in the annotated URL above, you can download it by yourself, you can also use this directly, * Public Base64coder class (do not delve into how it is implemented, * or that sentence, there are wheels directly with the wheel), easy to use the dead ... * the pony is also shameless to quote the Web The things under the address,Roar ... * @Title: Base64coder.java * @Package Com.xiaoma.piccut.demo * @Description: TODO * @author xiaoma/public class Base64coder {//the Line separator string of the operating system. Private static final String systemlineseparator = Syste
M.getproperty ("Line.separator");
Mapping table from 6-bit nibbles to Base64 characters.
private static char[] Map1 = new char[64];
  static {int i=0;
  for (char c= ' A '; c<= ' Z '; c + +) map1[i++] = C;
  for (Char c= ' a '; c<= ' z '; c + +) map1[i++] = C;
  for (char c= ' 0 '; c<= ' 9 '; C + +) map1[i++] = C; map1[i++] = ' + '; map1[i++] = '/';
}//mapping table from Base64 characters to 6-bit nibbles.
private static byte[] Map2 = new byte[128];
  static {for (int i=0; i<map2.length; i++) Map2[i] =-1; for (int i=0; i<64; i++) map2[map1[i] = (byte) i;
/** * Encodes a string into Base64 format.
* No blanks or line breaks are inserted.
* @param s A String to be encoded.
* @return A String containing the BASE64 encoded data. */public static STring encodestring (string s) {return new String (Encode (S.getbytes ())),/** * Encodes a byte array into Base format
And breaks the output into lines of the characters.
* This is compatible with Sun.misc.BASE64Encoder.encodeBuffer (byte[]).
* @param in a array containing the data bytes to be encoded.
* @return A String containing the BASE64 encoded data, broken into lines. */public static String Encodelines (byte[] in) {return encodelines (in, 0, In.length,, systemlineseparator);}/** * E
Ncodes a byte array into Base, format and breaks the output into lines.
* @param in a array containing the data bytes to be encoded.
* @param ioff Offset of the ' the ' the ' the ' the ' in ' <code>in</code> to is processed. * @param ilen Number of bytes to is processed in <code>in</code>, starting at <code>ioff</code&gt
;. * @param linelen line length for the output data.
Should be a multiple of 4. * @param lineseparator the line separator to be usedTo separate the output lines.
* @return A String containing the BASE64 encoded data, broken into lines. */public static String Encodelines (byte[] in, int ioff, int ilen, int linelen, String lineseparator) {int blocklen = (l
INELEN*3)/4;
if (Blocklen <= 0) throw new IllegalArgumentException ();
int lines = (ilen+blocklen-1)/Blocklen;
int buflen = ((ilen+2)/3) *4 + lines*lineseparator.length ();
StringBuilder buf = new StringBuilder (Buflen);
int ip = 0;
  while (IP < ilen) {int L = math.min (Ilen-ip, Blocklen);
  Buf.append (Encode (in, Ioff+ip, L));
  Buf.append (LineSeparator); IP + L; return buf.tostring ();
/** * Encodes a byte array into Base64 format.
* No blanks or line breaks are inserted in the output.
* @param in a array containing the data bytes to be encoded.
* @return A character array containing the BASE64 encoded data. * * public static char[] encode (byte[] in) {return encode (in, 0, in.length);}/** * encodes a byte array into Base64 for
Mat. * No BLAnks or line breaks are inserted in the output.
* @param in a array containing the data bytes to be encoded.
* @param ilen Number of bytes to process in <code>in</code>.
* @return A character array containing the BASE64 encoded data. * * public static char[] encode (byte[] in, int ilen) {return encode (in, 0, Ilen);}/** * encodes a byte array into Base6
4 format.
* No blanks or line breaks are inserted in the output.
* @param in a array containing the data bytes to be encoded.
* @param ioff Offset of the ' the ' the ' the ' the ' in ' <code>in</code> to is processed.
* @param ilen Number of bytes to process in <code>in</code>, starting at <code>ioff</code>.
* @return A character array containing the BASE64 encoded data.    */public static char[] encode (byte[] in, int ioff, int ilen) {int odatalen = (ilen*4+2)/3;     Output length without padding int oLen = ((ilen+2)/3) *4;
Output length including padding char[] out = new Char[olen]; int IP = Ioff;
int iend = Ioff + Ilen;
int op = 0;
  while (IP < iend) {int i0 = in[ip++] & 0xff; int i1 = IP < iend?
  in[ip++] & 0xff:0; int i2 = IP < iend?
  in[ip++] & 0xff:0;
  int o0 = I0 >>> 2; int O1 = ((I0 & 3) << 4) |
  (I1 >>> 4); int O2 = ((I1 & 0xf) << 2) |
  (I2 >>> 6);
  int O3 = i2 & 0x3F;
  out[op++] = Map1[o0];
  out[op++] = Map1[o1]; OUT[OP] = Op < odatalen? MAP1[O2]: ' = ';
  op++; OUT[OP] = Op < odatalen? MAP1[O3]: ' = '; op++; } return out;
}/** * Decodes a string from Base64 format.
* No blanks or line breaks are allowed within the BASE64 input data.
* @param s A Base64 String to be decoded.
* @return A String containing the decoded data.
* @throws illegalargumentexception If The input is not valid BASE64 encoded data. */public static string decodestring (String s) {return new String (decode (s));/** * Decodes a byte array from Base64 F Ormat and ignores line separators, tabs and blanks.
* CR, LF, Tab and space characters are ignored in the input data.
* This are compatible with <code>sun.misc.base64decoder.decodebuffer (String) </code>.
* @param s A Base64 String to be decoded.
* @return An array containing the decoded data bytes.
* @throws illegalargumentexception If The input is not valid BASE64 encoded data. */public static byte[] Decodelines (String s) {char[] buf = new Char[s.length () +3], int p = 0; for (int ip = 0; IP < S.length ();
  ip++) {char c = s.charat (IP); if (c!= ' && C!= ' \ r ' && c!= ' \ n ' && c!= ' t ') buf[p++] = C;
While ((p% 4)!= 0) buf[p++] = ' 0 '; Return decode (buf, 0, p);
}/** * Decodes a byte array from Base64 format.
* No blanks or line breaks are allowed within the BASE64 input data.
* @param s A Base64 String to be decoded.
* @return An array containing the decoded data bytes. * @throws illegalargumentexception If The input is not valid BASE64 encodeD data. */public static byte[] Decode (String s) {return decode (S.tochararray ());}/** * Decodes A-byte array from Base64 forma
T. * No blanks or line breaks are allowed within the BASE64 encoded input data.
* @param in A character array containing the BASE64 encoded data.
* @return An array containing the decoded data bytes.
* @throws illegalargumentexception If The input is not valid BASE64 encoded data. * * public static byte[] Decode (char[] in) {return decode (in, 0, in.length);}/** * Decodes a byte array from Base64 for
Mat.
* No blanks or line breaks are allowed within the BASE64 input data.
* @param in A character array containing the BASE64 encoded data.
* @param ioff Offset of the ' the ' the ' the ' the ' the ' the ' character ' is processed.
* @param ilen number of characters to process in <code>in</code>, starting at <code>ioff</code>.
* @return An array containing the decoded data bytes. * @throws IllegalArgumentException If the InThe ' is ' not valid BASE64 encoded data. */public static byte[] Decode (char[] in, int ioff, int ilen) {if (ilen%4!= 0) throw new IllegalArgumentException ("Len
Gth of BASE64 encoded input string is not a multiple of 4. ");
while (Ilen > 0 && in[ioff+ilen-1] = = ' = ') ilen--;
int oLen = (ilen*3)/4;
Byte[] out = new Byte[olen];
int ip = ioff;
int iend = Ioff + Ilen;
int op = 0;
  while (IP < iend) {int i0 = in[ip++];
  int i1 = in[ip++]; int i2 = IP < iend?
  in[ip++]: ' A '; int i3 = IP < iend?
  in[ip++]: ' A ';  if (I0 > 127 | | i1 > 127 | | i2 > 127 | | i3 > 127) throw new IllegalArgumentException ("illegal character in
  BASE64 encoded data. ");
  int b0 = Map2[i0];
  int b1 = Map2[i1];
  int b2 = Map2[i2];
  int b3 = Map2[i3]; if (B0 < 0 | | B1 < 0 | | B2 < 0 | | B3 < 0) throw new illegalargumentexception ("illegal character in Base64
  Encoded data. "); int o0 = (B0 <<2) |
  (B1&GT;&GT;&GT;4); int O1 = ((B1 & 0xf) <<4)|
  (B2&GT;&GT;&GT;2); int O2 = ((B2 & 3) <<6) |
  B3;
  out[op++] = (byte) o0;
  if (Op<olen) out[op++] = (byte) O1; if (Op<olen) out[op++] = (byte) O2; } return out;
}//dummy constructor.

 Private Base64coder () {}}//End Class Base64coder

For more information on Android-related content readers can view the site: "Android graphics and image processing skills summary", "Android Development introduction and Advanced Course", "Android debugging techniques and common problems solution summary", " Android Multimedia How-to Summary (audio, video, audio, etc), summary of Android Basic components usage, Android View tips Summary, Android layout layout tips and a summary of Android controls usage

I hope this article will help you with the Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.