Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android拍照選擇圖庫後將照片剪裁壓縮顯示到imageview上

android拍照選擇圖庫後將照片剪裁壓縮顯示到imageview上

編輯:關於Android編程

調用圖庫和拍照的時候權限:





 

java 代碼:


public class KujieSY extends Activity implements OnClickListener{
/** (非 Javadoc)
* 方法名: onCreate
* 描述:
* 作者 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);
}
/** (非 Javadoc)
* 方法名: onClick
* 描述:
* 作者 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("選擇傳圖方式")
.setIcon(R.drawable.logoyy)
.setPositiveButton("圖庫選擇",
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("拍照", 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;
}

/** (非 Javadoc)
* 方法名: onActivityResult
* 描述:
* 作者 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, null, 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;
}
}
/**
*
* @方法名: startPhotoZoom
* @描述: TODO(裁剪照片)
* @作者 張麗平
* @參數 @param uri
* @返回值 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 是寬高的比例
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
// // outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", 128);
intent.putExtra("outputY", 128);
intent.putExtra("return-data", true);
startActivityForResult(intent, 3);
}

}

壓縮圖片:

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;
}


/**
* 從文件或Uri獲得Bitmap 限制像素大小(maxResolutionX*maxResolutionY)
* 限制最小邊長min(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;
}


/** 計算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);
}


/** 計算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;
}


/** 計算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;
}
}


/** 保存Bitmap到Uri地址【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;
}
}
}


/** 關閉流文件 */
private static void closeSilently(Closeable c) {
if (c == null)
return;
try {
c.close();
} catch (Throwable t) {
}
}


}

xml 代碼:


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="快捷收銀"
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="商戶名稱:"
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"
/>






 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved