android拍照选择图库后将照片剪裁压缩显示到imageview上
调用图库和拍照的时候权限:
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
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 代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#006dba"
android:padding="5dip" >
<TextView
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" />
<TextView
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" />
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dip"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="10dip"
android:orientation="horizontal"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="商户名称:"
android:textColor="#000000"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/shanghuname"
android:background="@drawable/xian"
/>
</LinearLayout>
<ImageView
android:layout_width="100dip"
android:layout_height="100dip"
android:id="@+id/images"
android:scaleType="centerInside"
android:src="@drawable/chongzhi"
/>
</LinearLayout>
</ScrollView>
</LinearLayout>
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。