After selecting the image library for android photos, you can crop and compress the photos and display them to the imageview.
Permission for calling Image Library and photo taking:
Java code:
Public class KujieSY extends Activity implements OnClickListener {
/** (Non-Javadoc)
* Method name: onCreate
* Description:
* Author vencent
* @ Param savedInstanceState
* @ See android. app. Activity # onCreate (android. OS. Bundle)
*/
Private TextView backs;
Private ImageView images;
String takephoto = "";
File PicFile;
KujieSY self = KujieSY. this;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
// TODO Auto-generated method stub
Super. onCreate (savedInstanceState );
SetContentView (R. layout. kuaijieshouyin );
InitView ();
}
Public void initView (){
Backs = (TextView) findViewById (R. id. backs );
Images = (ImageView) findViewById (R. id. images );
Backs. setOnClickListener (this );
Images. setOnClickListener (this );
}
/** (Non-Javadoc)
* Method name: onClick
* Description:
* Author vencent
* @ Param arg0
* @ See android. view. View. OnClickListener # onClick (android. view. View)
*/
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
Switch (v. getId ()){
Case R. id. backs:
Finish ();
Break;
Case R. id. images:
New AlertDialog. Builder (this)
. SetTitle ("select Image Upload mode ")
. SetIcon (R. drawable. logoyy)
. SetPositiveButton ("select Image Library ",
New DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface arg0,
Int arg1 ){
Intent intent = new Intent (Intent. ACTION_PICK, null );
Intent. setDataAndType (
MediaStore. Images. Media. EXTERNAL_CONTENT_URI,
"Image /*");
StartActivityForResult (intent, 1 );
}
}). SetNegativeButton ("photo", new DialogInterface. OnClickListener (){
@ Override
Public void onClick (DialogInterface arg0, int arg1 ){
// TODO Auto-generated method stub
Takephoto = savepic ();
Intent imageCaptureIntent = new Intent (MediaStore. ACTION_IMAGE_CAPTURE );
ImageCaptureIntent. putExtra (MediaStore. EXTRA_OUTPUT,
Uri. fromFile (PicFile ));
ImageCaptureIntent. putExtra ("android. intent. extra. videoQuality", 0 );
StartActivityForResult (imageCaptureIntent, 2 );
}
}). Show ();
Break;
}
}
Public String savepic (){
File files = new File (IMP. saveimages );
If (! Files. exists ()){
Files. mkdirs ();
}
String picpath = IMP. saveimages + "/" + System. currentTimeMillis () + ". jpg ";
PicFile = new File (picpath );
Return picpath;
}
/** (Non-Javadoc)
* Method name: onActivityResult
* Description:
* Author vencent
* @ Param requestCode
* @ Param resultCode
* @ Param data
* @ See android. app. Activity # onActivityResult (int, int, android. content. Intent)
*/
@ Override
Protected void onActivityResult (int requestCode, int resultCode, Intent data ){
// TODO Auto-generated method stub
Super. onActivityResult (requestCode, resultCode, data );
If (resultCode = 0 ){
Return;
}
Switch (requestCode ){
Case 1:
Uri selectedImage = data. getData ();
String [] filePathColumn = {MediaStore. Images. Media. DATA };
Cursor cursor = getContentResolver (). query (selectedImage,
FilePathColumn, null );
Cursor. moveToFirst ();
Int columnIndex = cursor. getColumnIndex (filePathColumn [0]);
String picturePath = cursor. getString (columnIndex );
// Bitmap bitmap = getLoacalBitmap (data. getDataString ());
String newfileselect = IMP. saveimages + "/" + System. currentTimeMillis () + ". jpg ";
ImageCrop. Crop (self, picturePath, newfileselect );
Images. setImageBitmap (BitmapFactory. decodeFile (newfileselect ));
Break;
Case 2:
String newfile = IMP. saveimages + "/" + System. currentTimeMillis () + ". jpg ";
ImageCrop. Crop (self, PicFile. getAbsolutePath (), newfile );
Images. setImageBitmap (BitmapFactory. decodeFile (newfile ));
Break;
}
}
/**
*
* @ Method Name: startPhotoZoom
* @ Description: TODO (crop a photo)
* @ Author Zhang Liping
* @ Parameter @ param uri
* @ Return value void
* @ Throws
*/
Public void startPhotoZoom (Uri uri ){
Intent intent = new Intent ("com. android. camera. action. CROP ");
Intent. setDataAndType (uri, "image /*");
Intent. putExtra ("crop", "true ");
// AspectX aspectY is the aspect ratio
Intent. putExtra ("aspectX", 1 );
Intent. putExtra ("aspectY", 1 );
/// OutputX outputY indicates the width and height of the cropped image.
Intent. putExtra ("outputX", 128 );
Intent. putExtra ("outputY", 128 );
Intent. putExtra ("return-data", true );
StartActivityForResult (intent, 3 );
}
}
Compressed image:
Package com. jfy. app;
Import java. io. BufferedInputStream;
Import java. io. Closeable;
Import java. io. File;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. URISyntaxException;
Import org. apache. http. conn. ClientConnectionManager;
Import android. content. ContentResolver;
Import android. content. Context;
Import android. graphics. Bitmap;
Import android. graphics. BitmapFactory;
Import android. media. ThumbnailUtils;
Import android.net. Uri;
Public class ImageCrop {
Public static boolean Crop (Context context, String pathName,
String newPathName ){
Return Crop (context, pathName, newPathName, 1024 );
}
Public static boolean Crop (Context context, String pathName,
String newPathName, int maxXY ){
File fielName = new File (pathName );
File newFielName = new File (newPathName );
File newParentFile = newFielName. getParentFile ();
If (! FielName. exists ()){
Return false;
}
If (! NewParentFile. exists ()){
NewParentFile. mkdirs ();
}
Try {
Bitmap mBitmap = createFromUri (context, Uri. fromFile (fielName)
. ToString (), 2 * maxXY, 2 * maxXY, 0, null );
If (mBitmap = null ){
Return false;
}
Bitmap B = null;
If (mBitmap. getWidth ()> mBitmap. getHeight ()
& MBitmap. getWidth ()> maxXY ){
Int tempHiget = maxXY * mBitmap. getHeight ()
/MBitmap. getWidth ();
B = ThumbnailUtils. extractThumbnail (mBitmap, maxXY, tempHiget );
} Else if (mBitmap. getHeight ()> mBitmap. getWidth ()
& MBitmap. getHeight ()> maxXY ){
Int tempWidth = maxXY * mBitmap. getWidth ()
/MBitmap. getHeight ();
B = ThumbnailUtils. extractThumbnail (mBitmap, tempWidth, maxXY );
}
If (B! = Null & mBitmap! = B ){
MBitmap. recycle ();
MBitmap = B;
}
SaveOutput (context, mBitmap, newFielName );
Return true;
} Catch (Exception e ){
If (newFielName. exists ()){
NewFielName. delete ();
}
}
Return false;
}
/**
* Getting Bitmap from a file or Uri limits the pixel size (maxResolutionX * maxResolutionY)
* Min limit (maxResolutionX * maxResolutionY)/2
*/
Private static final Bitmap createFromUri (Context context, String uri,
Int maxResolutionX, int maxResolutionY, long cacheId,
ClientConnectionManager connectionManager) throws IOException,
URISyntaxException, OutOfMemoryError {
Final BitmapFactory. Options options = new BitmapFactory. Options ();
Options. inScaled = false;
Options. inPreferredConfig = Bitmap. Config. RGB_565;
Options. inDither = true;
Bitmap bitmap = null;
// Get the input stream for computing the sample size.
BufferedInputStream bufferedInput = null;
If (uri. startsWith (ContentResolver. SCHEME_CONTENT)
| Uri. startsWith (ContentResolver. SCHEME_FILE )){
// Get the stream from a local file.
BufferedInput = new BufferedInputStream (context
. GetContentResolver (). openInputStream (Uri. parse (uri )),
16384 );
} Else {
Return null;
}
// Compute the sample size, I. e., not decoding real pixels.
If (bufferedInput! = Null ){
Options. inSampleSize = computeSampleSize (bufferedInput,
MaxResolutionX, maxResolutionY );
} Else {
Return null;
}
// Get the input stream again for decoding it to a bitmap.
BufferedInput = null;
If (uri. startsWith (ContentResolver. SCHEME_CONTENT)
| Uri. startsWith (ContentResolver. SCHEME_FILE )){
// Get the stream from a local file.
BufferedInput = new BufferedInputStream (context
. GetContentResolver (). openInputStream (Uri. parse (uri )),
16384 );
} Else {
Return null;
}
// Decode bufferedInput to a bitmap.
If (bufferedInput! = Null ){
Options. inDither = false;
Options. inJustDecodeBounds = false;
Thread timeoutThread = new Thread ("BitmapTimeoutThread "){
Public void run (){
Try {
Thread. sleep (6000 );
Options. requestCancelDecode ();
} Catch (InterruptedException e ){
}
}
};
TimeoutThread. start ();
Bitmap = BitmapFactory. decodeStream (bufferedInput, null, options );
CloseSilently (bufferedInput );
}
Return bitmap;
}
/** Calculate SampleSize [1 ]*/
Private static int computeSampleSize (InputStream stream,
Int maxResolutionX, int maxResolutionY ){
BitmapFactory. Options options = new BitmapFactory. Options ();
Options. inJustDecodeBounds = true;
BitmapFactory. decodeStream (stream, null, options );
Int maxNumOfPixels = maxResolutionX * maxResolutionY;
Int minSideLength = Math. min (maxResolutionX, maxResolutionY)/2;
Return UtilscomputeSampleSize (options, minSideLength, maxNumOfPixels );
}
/** Calculate SampleSize [2 ]*/
Private static int UtilscomputeSampleSize (BitmapFactory. Options options,
Int minSideLength, int maxNumOfPixels ){
Int initialSize = computeInitialSampleSize (options, minSideLength,
MaxNumOfPixels );
Int roundedSize;
If (initialSize <= 8 ){
RoundedSize = 1;
While (roundedSize <initialSize ){
RoundedSize <= 1;
}
} Else {
RoundedSize = (initialSize + 7)/8*8;
}
Return roundedSize;
}
/** Calculate SampleSize [3 ]*/
Private static int computeInitialSampleSize (BitmapFactory. Options options,
Int minSideLength, int maxNumOfPixels ){
Final int UNCONSTRAINED =-1;
Double w = options. outWidth;
Double h = options. outHeight;
Int lowerBound = (maxNumOfPixels = UNCONSTRAINED )? 1: (int) Math
. Ceil (Math. sqrt (w * h/maxNumOfPixels ));
Int upperBound = (minSideLength = UNCONSTRAINED )? 128: (int) Math
. Min (Math. floor (w/minSideLength ),
Math. floor (h/minSideLength ));
If (upperBound <lowerBound ){
// Return the larger one when there is no overlapping zone.
Return lowerBound;
}
If (maxNumOfPixels = UNCONSTRAINED)
& (MinSideLength = UNCONSTRAINED )){
Return 1;
} Else if (minSideLength = UNCONSTRAINED ){
Return lowerBound;
} Else {
Return upperBound;
}
}
/** Save Bitmap to Uri Address [content: // or file: //; "image/*" or "JPEG "]*/
Private static void saveOutput (Context context, Bitmap mBitmap,
File newFielName ){
OutputStream outputStream = null;
Try {
OutputStream = context. getContentResolver (). openOutputStream (
Uri. fromFile (newFielName ));
If (outputStream! = Null ){
MBitmap. compress (Bitmap. CompressFormat. valueOf ("JPEG"), 85,
OutputStream );
}
} Catch (IOException ex ){
} Finally {
CloseSilently (outputStream );
If (mBitmap! = Null ){
MBitmap. recycle ();
MBitmap = null;
}
}
}
/** Close the stream file */
Private static void closeSilently (Closeable c ){
If (c = null)
Return;
Try {
C. close ();
} Catch (Throwable t ){
}
}
}
Xml code:
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: background = "# f0f0f0"
Android: orientation = "vertical">
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: layout_gravity = "top"
Android: background = "# 006dba"
Android: padding = "5dip">
Android: id = "@ + id/backs"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: drawableLeft = "@ drawable/back"
Android: paddingBottom = "5dip"
Android: paddingLeft = "5dip"
Android: paddingRight = "20dip"
Android: paddingTop = "5dip"/>
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: layout_centerInParent = "true"
Android: layout_weight = "1"
Android: text = "quick cashier"
Android: textColor = "# ffffff"
Android: textSize = "20sp"/>
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
>
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "vertical"
Android: padding = "10dip"
>
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"
Android: paddingBottom = "10dip"
Android: orientation = "horizontal"
>
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "Merchant name :"
Android: textColor = "#000000"
/>
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: id = "@ + id/shanghuname"
Android: background = "@ drawable/xian"
/>
Android: layout_width = "100dip"
Android: layout_height = "100dip"
Android: id = "@ + id/images"
Android: scaleType = "centerInside"
Android: src = "@ drawable/chongzhi"
/>