Android calls system camera to take photos and trim compression

Source: Internet
Author: User

As the business needs to write an Android phone to take pictures of the function demo, while achieving the picture clipping and image compression. The following is the source


package com.klp.demo_025;import java.io.bytearrayinputstream;import  java.io.bytearrayoutputstream;import java.io.file;import java.io.fileoutputstream;import  android.app.activity;import android.content.intent;import android.graphics.bitmap;import  android.graphics.bitmapfactory;import android.net.uri;import android.os.bundle;import  android.provider.mediastore;import android.view.view;import android.widget.button;import  android.widget.imageview;public class mainactivity extends activity {     private ImageView iv;    private Button button;     private File file;    private Uri uri;      @Override     protected void oncreate (bundle savedinstancestate)  {        super.oncreate (SavedInstancestate);         setcontentview (R.layout.activity_main);         iv =  (ImageView)  findviewbyid (r.id.imageview1);         button =  (Button)  findviewbyid (r.id.button1);         file = new file (This.getexternalfilesdir (NULL),  "Image.jpg");         uri = uri.fromfile (file);         button.setonclicklistener (New view.onclicklistener ()  {              @Override              public void onclick (VIEW V)  {                 // todo auto-generated  method stub&nbsP;               intent intent  = new intent (mediastore.action_image_capture);                 intent.putextra (mediastore.images.media.orientation, 0);                  Intent.putextra (Mediastore.extra_output, uri);                 startactivityforresult (intent, 2);             }        });     }     @Override     protected void  Onactivityresult (Int requestcode, int resultcode, intent data)  {         // todo&nbsP Auto-generated method stub        super.onactivityresult ( Requestcode, resultcode, data);        if  (resultCode  == RESULT_OK)  {            if   (REQUESTCODE == 2)  {                 startphotozoom (URI);             } else {                 try {                     BitmapFactory.Options options = new  Bitmapfactory.options ();                     options.insamplesize = 2;                     bitmap bitmap = bitmapfactory.decodefile (File.getPath (),                             options);                     //  Compress picture//                      bitmap = compressimage (bitmap,500);                     if  (bitmap != null)  {                          //  Show Pictures                          iv.setimagebitmap (bitmap);                         //   Save Pictures                          FileOutputStream fos = null;                          fos = new fileoutputstream (file);                          Bitmap.compress (Bitmap.compressformat.jpeg, 100, fos);             &Nbsp;           fos.flush ();                          fos.close ();                     }                 } catch  (exception e)  {                     // TODO: handle  exception                }             }         }    }    /**     *  Crop Pictures      *      *  @param  uri     */     public void startphotozoom (Uri uri)  {         intent intent = new intent ("Com.android.camera.action.CROP");         intent.setdataandtype (uri,  "image/*");         intent.putextra ("Crop",  "true");// crop=true  have this sentence to come out the last cropped page .         intent.putextra ("Aspectx",  1);//  These two are the proportions of the cropping box .         intent.putextra ("Aspecty",  1);// x:y=1:1         intent.putextra ("Outputx",  200);//Picture output size          Intent.putextra ("Outputy",  200);         intent.putextra ("Output",  uri);    &nbsP;    intent.putextra ("OutputFormat",  "JPEG");//  return format          startactivityforresult (intent, 3);    }     /**     *  compress a picture image into a  size-sized picture (size represents a picture, in kilobytes)       *      *  @param  image     *              Photo Resources      * @ param size     *              picture size      *  @return  Bitmap     */     private bitmap compressimage (bitmap image, int size)  {         ByteArrayOutputStream baos = new  Bytearrayoutputstream ();         //  mass compression method, where 100 means no compression, the compressed data stored in the BAOs          image.compress (Bitmap.compressformat.jpeg, 100, baos);         int options = 100;        //  The loop determines if the compressed image is greater than 100kb, which is larger than the continue compression         while  (Baos.tobytearray (). Length / 1024 > size)  {             //  Reset BAOs is empty baos             baos.reset ();            //  10 less each time             options -= 10;             //  compress the options% here and store the compressed data in the BAOs               image.compress (Bitmap.compressformat.jpeg, options, baos);         }        //  Store the compressed data BAOs in the Bytearrayinputstream         ByteArrayInputStream  Isbm = new bytearrayinputstream (Baos.tobytearray ());         //  Bytearrayinputstream data Generation image         bitmap bitmap  = bitmapfactory.decodestream (isbm, null, null);         return bitmap;    }}

Here is the layout, very simple

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"      xmlns:tools= "Http://schemas.android.com/tools"     android:layout_width= "Match_parent"     android:layout_height= "Match_parent"     tools:context= "${ Relativepackage}.${activityclass} " >    <ImageView         android:id= "@+id/imageview1"         android: Layout_width= "200DP"         android:layout_height= "200DP"          android:layout_alignparenttop= "true"          android:layout_centerhorizontal= "true"         android: layout_margintop= "64DP"         android:src= "@drawable/ic_launcher"  />    <button&Nbsp;       android:id= "@+id/button1"          android:layout_width= "Wrap_content"         android:layout_ height= "Wrap_content"         android:layout_below= "@+id/imageView1"         android:layout_centerhorizontal= "true"          android:layout_margintop= "32DP"         android : text= "Photo"  /></RelativeLayout>

Finally, be sure to add the SD card access in Androidmanifest.xml:

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

This article is from the "Piggy Ben" blog, please be sure to keep this source http://6883741.blog.51cto.com/6873741/1596242

Android calls system camera to take photos and trim compression

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.