android 调用系统自带的选择图片 然后进行自定义大小裁剪

package com.test.www.xiangjixiangce;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


import com.test.www.ClipPictureActivity;
import com.test.www.R;


public class CAMERAPICTURE extends Activity implements OnClickListener{



Button btngocamer,btngopicture;
TextView tvback;
private int requestCodepick=100;

@SuppressWarnings("unused")
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.comecamer);
if(false){
return;
}
initView();

}


private void initView() {
btngocamer = (Button)findViewById(R.id.btngocamer);
btngopicture = (Button)findViewById(R.id.btngopicture);
tvback = (TextView)findViewById(R.id.tvback);
btngopicture.setOnClickListener(this);
tvback.setOnClickListener(this);
}


@Override
protected void onDestroy() {
super.onDestroy();
}


@Override
protected void onResume() {
super.onResume();
}


public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.btngocamer:

break;
case R.id.btngopicture:

Intent intentpic = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intentpic, requestCodepick);
break;
case R.id.tvback:
finish();
break;
default:
break;
}
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==requestCode&& data!=null&&resultCode==Activity.RESULT_OK){
Uri selectimg = data.getData(); 
String  [] filepathcloum ={MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(selectimg, filepathcloum, null, null, null);
cursor.moveToNext();
int columnIndex = cursor.getColumnIndex(filepathcloum[0]);
String columnpath = cursor.getString(columnIndex);
cursor.close();

Intent intentClipPic= new Intent();
intentClipPic.setClass(CAMERAPICTURE.this, ClipPictureActivity.class);
intentClipPic.putExtra("columnpath", columnpath);
startActivity(intentClipPic);
}
}




}


package com.test.www;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


public class ClipPictureActivity extends Activity implements OnTouchListener, OnClickListener {
ImageView srcPic;
Button sure;
ClipView clipview;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
Matrix matrixxuanzhuan = new Matrix();
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
static final int XUANZ = 3;
private static final String TAG = "11";
int mode = NONE;
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
private String intentpath;
private float x_down;
private float y_down;
float oldRotation = 0;
private Bitmap bitmap;
boolean matrixCheck = false;
private Button xuanz;
private int widthx;
private int heighty;
int statusBarHeight = 0;
int titleBarHeight = 0;
private Bitmap newbitmap;
// public static int titleBarHeights;
// public static int statusBarHeights;
private int BarHeights;
private FileOutputStream fos;
private File file;
private File path;
private static int degree=0;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = getIntent();
intentpath = intent.getStringExtra("columnpath");
getBarHeight();
getPingmuxiangsu();
xuanz = (Button) this.findViewById(R.id.xuanz);
if (intentpath != null) {
srcPic = (ImageView) this.findViewById(R.id.src_pic);
srcPic.setOnTouchListener(this);
File file = new File(intentpath);
if (file.exists()) {
BitmapFactory.Options opts = new BitmapFactory.Options();// 获取缩略图显示到屏幕上
opts.inSampleSize = 2;
bitmap = BitmapFactory.decodeFile(intentpath,opts);
srcPic.setImageBitmap(bitmap);

// RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(widthx,heighty+BarHeights); 
// lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); 
// lp.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE); 
// lp.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE); 
// srcPic.setLayoutParams(lp);

// MarginLayoutParams margin9 = new MarginLayoutParams(
// srcPic.getLayoutParams());
// margin9.setMargins(widthx/2-ClipView.x/2,(heighty)/2-ClipView.y/2,widthx/2-ClipView.x/2,(
// heighty)/2-ClipView.y/2);//在左边距400像素,顶边距10像素的位置显示图片
// RelativeLayout.LayoutParams layoutParams9 = new RelativeLayout.LayoutParams(margin9);
// layoutParams9.width = ClipView.x; //设置图片的宽度
// layoutParams9.height =ClipView.y;//设置图片的高度
// srcPic.setLayoutParams(layoutParams9);
}
}
xuanz.setOnClickListener(this);
sure = (Button) this.findViewById(R.id.sure);
sure.setOnClickListener(this);
}

public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.sure:
Bitmap fianBitmap = getBitmap();
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// fianBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// byte[] bitmapByte = baos.toByteArray();
String SavePath = getSDCardPath() + "/AndyDemo/ScreenImage";
try {
path = new File(SavePath);
// 文件
String filepath = SavePath + "/Screen_1.png";
file = new File(filepath);
Log.i(TAG, "filepath=====" + filepath);
if (!path.exists()) {
Log.i(TAG, "2_1");
path.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
if (null != fos) {
// Bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
// byte[] bitmapByte = fos.toByteArray();
//压缩
fianBitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
Toast.makeText(ClipPictureActivity.this, "截屏文件已保存至" + SavePath,
Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), PreviewActivity.class);
intent.putExtra("filepath", filepath);
startActivity(intent);
}


} catch (Exception e) {
e.printStackTrace();
Toast.makeText(ClipPictureActivity.this, "/?????" + SavePath,
Toast.LENGTH_LONG).show();
}

break;
case R.id.xuanz:
degree = readPictureDegree(intentpath);
System.out.println("degree::::"+degree);
degree+=90;
System.out.println("degree===:"+degree);
BitmapFactory.Options opts = new BitmapFactory.Options();// 获取缩略图显示到屏幕上
opts.inSampleSize = 2;
bitmap = BitmapFactory.decodeFile(intentpath, opts);
newbitmap = rotaingImageView(degree, bitmap);
srcPic.setImageBitmap(newbitmap);
break;
default:
break;
}
}


public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
// srcPic.setScaleType(ScaleType.MATRIX);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: // 用户开始触摸
savedMatrix.set(matrix); // 设置Matrix中的值
start.set(event.getX(), event.getY()); // 设置Matrix中的值
x_down = event.getX();
y_down = event.getY();

// //获取这个图片的宽和高
// int width = srcPic.getWidth();
// int height = srcPic.getHeight();
// //定义预转换成的图片的宽度和高度
// int newWidth = 200;
// int newHeight = 200;
// float scaleWidth = ((float) newWidth) / width;
// float scaleHeight = ((float) newHeight) / height;
// matrixxuanzhuan.postScale(scaleWidth, scaleHeight);
// //旋转图片 动作
// matrix.postRotate(45);
// // 创建新的图片
// //将上面创建的Bitmap转换成Drawable对象,使得其可以使用在ImageView, ImageButton中
mode = DRAG;// =1
break;
case MotionEvent.ACTION_POINTER_DOWN:// 有一个非主要的手指按下了
oldDist = spacing(event);
oldRotation = rotation(event);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:// 用户抬起了手指
case MotionEvent.ACTION_POINTER_UP:// 一个非主要的手指抬起来了
mode = NONE;// 0
break;
case MotionEvent.ACTION_MOVE: // 用户在移动(手指或者其他)
if (mode == DRAG) {// 1
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
} else if (mode == ZOOM) {// 2
float newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float rotation = rotation(event) - oldRotation;
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
// matrix.postRotate(rotation, mid.x, mid.y);// 旋轉
// matrixCheck = matrixCheck();
// if (matrixCheck == false) {
// matrix.set(matrix);
// // invalidate();
// }
}
}
break;
}
view.setImageMatrix(matrix);
return true; // indicate event was handled
}

private Bitmap getBitmap() {
getBarHeight();
Bitmap screenShoot = takeScreenShot();
clipview = (ClipView) this.findViewById(R.id.clipview);
getPingmuxiangsu();
Bitmap finalBitmap = Bitmap.createBitmap(screenShoot, widthx / 2 - ClipView.x / 2, (heighty + BarHeights) / 2 - ClipView.y / 2, ClipView.x, ClipView.y);
return finalBitmap;
}
private void getPingmuxiangsu(){
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
widthx = metric.widthPixels; // 屏幕宽度(像素)
heighty = metric.heightPixels; // 屏幕高度(像素)
System.out.println("widthx:" + widthx);
System.out.println("heighty:" + heighty);
}


private void getBarHeight() {
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
statusBarHeight = frame.top;
int contenttop = this.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
titleBarHeight = contenttop - statusBarHeight;
BarHeights = titleBarHeight+statusBarHeight;
System.out.println("BarHeights:" + BarHeights);
System.out.println("titleBarHeight:" + titleBarHeight);
System.out.println("statusBarHeight:" + statusBarHeight);
}


private boolean matrixCheck() {
float[] f = new float[9];
matrix.getValues(f);
// 图片4个顶点的坐标
float x1 = f[0] * 0 + f[1] * 0 + f[2];
float y1 = f[3] * 0 + f[4] * 0 + f[5];
float x2 = f[0] * bitmap.getWidth() + f[1] * 0 + f[2];
float y2 = f[3] * bitmap.getWidth() + f[4] * 0 + f[5];
float x3 = f[0] * 0 + f[1] * bitmap.getHeight() + f[2];
float y3 = f[3] * 0 + f[4] * bitmap.getHeight() + f[5];
float x4 = f[0] * bitmap.getWidth() + f[1] * bitmap.getHeight() + f[2];
float y4 = f[3] * bitmap.getWidth() + f[4] * bitmap.getHeight() + f[5];
// 图片现宽度
double width = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
// 缩放比率判断
if (width < widthx / 3 || width > widthx * 3) {
return true;
}
// 出界判断
if ((x1 < widthx / 3 && x2 < widthx / 3 && x3 < widthx / 3 && x4 < widthx / 3) || (x1 > widthx * 2 / 3 && x2 > widthx * 2 / 3 && x3 > widthx * 2 / 3 && x4 > widthx * 2 / 3) || (y1 < heighty / 3 && y2 < heighty / 3 && y3 < heighty / 3 && y4 < heighty / 3) || (y1 > heighty * 2 / 3 && y2 > heighty * 2 / 3 && y3 > heighty * 2 / 3 && y4 > heighty * 2 / 3)) {
return true;
}
return false;
}


private float rotation(MotionEvent event) {
double delta_x = (event.getX(0) - event.getX(1));
double delta_y = (event.getY(0) - event.getY(1));
double radians = Math.atan2(delta_y, delta_x);
return (float) Math.toDegrees(radians);
}


/** Determine the space between the first two fingers */
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}


/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}


private String getSDCardPath() {
File sdcardDirFile = null;
boolean sdcardexits = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
if (sdcardexits) {
sdcardDirFile = Environment.getExternalStorageDirectory();


}else {
Toast.makeText(this, "没有SD卡", Toast.LENGTH_SHORT).show();
}
return sdcardDirFile.toString();
}









public static int readPictureDegree(String path) {
// int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
// degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
// degree = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
// degree = 90;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}


public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
// 旋转图片 动作
Matrix matrix = new Matrix();
matrix.postRotate(angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}


private Bitmap takeScreenShot() {
View view = this.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
return view.getDrawingCache();
}





}



package com.test.www;


import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.view.Window;


public class ClipView extends View
{
public static int x=400;
public static int y=500;
// public static int titleBarHeights;
// public static int statusBarHeights;
public Context context;
private Activity activity;
private int statusBarHeight =0;
private int titleBarHeight=0;



public ClipView(Context context)
{
super(context);
this.context = context;
System.out.println(":::::::::");

}
public ClipView(Context context,Activity activity)
{
super(context);
this.context = context;
this.activity = activity;
System.out.println(":::::::::");

}


public ClipView(Context context, AttributeSet attrs)
{
super(context, attrs);
this.context = context;
System.out.println(":::::::::");
}




public ClipView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
this.context = context;
System.out.println(":::::::::");
}



@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
// getBarHeight();
int width = this.getWidth();
int height = this.getHeight();
System.out.println("width::==========="+width);
System.out.println("height::=========="+height);
System.out.println("statusBarHeight::=========="+statusBarHeight);
System.out.println("titleBarHeight::=========="+titleBarHeight);
Paint paint = new Paint();
paint.setColor(0xaa000000);
// paint.setColor(getResources().getColor(R.color.white_tran_text));
// paint.setColor(getResources().getColor(R.color.touming));
// canvas.drawRect(width/2-x/2, height/2-y/2, width/2+x/2, height/2+y/2, paint);
//top
canvas.drawRect(0, 0, width, (height+statusBarHeight+titleBarHeight)/2-y/2, paint);
//left
canvas.drawRect(0,  (height+statusBarHeight+titleBarHeight)/2-y/2,width/2-x/2, (height+statusBarHeight+titleBarHeight)/2+y/2, paint);
//right
canvas.drawRect(width/2+x/2,(height+statusBarHeight+titleBarHeight)/2-y/2,width ,  (height+statusBarHeight+titleBarHeight)/2+y/2 , paint);
//bottom
canvas.drawRect(0, (height+statusBarHeight+titleBarHeight)/2+y/2, width, height+statusBarHeight+titleBarHeight, paint);

paint.setColor(getResources().getColor(R.color.white));
// TOP
canvas.drawRect(width/2-x/2-1,(height+statusBarHeight+titleBarHeight)/2-y/2-1 ,width/2+x/2,(height+statusBarHeight+titleBarHeight)/2-y/2, paint);
//left
canvas.drawRect(width/2-x/2-1, (height+statusBarHeight+titleBarHeight)/2-y/2,width/2-x/2, (height+statusBarHeight+titleBarHeight)/2+y/2, paint);
//right
canvas.drawRect(width/2+x/2,(height+statusBarHeight+titleBarHeight)/2-y/2,width/2+x/2+1,  (height+statusBarHeight+titleBarHeight)/2+y/2 , paint);
//bottom
canvas.drawRect(width/2-x/2, (height+statusBarHeight+titleBarHeight)/2+y/2, width/2+x/2, (height+statusBarHeight+titleBarHeight)/2+y/2+1, paint);

// //top
// canvas.drawRect(0, 0, width, height/3, paint);
// //left
// canvas.drawRect(0, height/3, (width - height/3)/2, height*2/3, paint);
// //right
// canvas.drawRect((width + height/3)/2, height/3, width ,  height*2/3, paint);
// //bottom
// canvas.drawRect(0, height*2/3, width, height, paint);
}



}


package com.test.www;


import java.io.File;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;


public class PreviewActivity extends Activity
{
ImageView preview;
private String mImgUrl;
private File file;


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.preview);
mImgUrl = getIntent().getStringExtra("filepath");
System.out.println("mImgUrl:"+mImgUrl);
if (null != mImgUrl) {
preview = (ImageView)findViewById(R.id.preview);
file = new File(mImgUrl);
if (file.exists()) {
Bitmap bm = BitmapFactory.decodeFile(mImgUrl);
Toast.makeText(this, "剪裁ok", Toast.LENGTH_SHORT).show();
preview.setImageBitmap(bm);
}else {
Toast.makeText(this, "! file.exists()", Toast.LENGTH_SHORT).show();
}
}else {
System.out.println("mImgUrl=null :");
}


// Bitmap bitmap = null;
// Intent in = getIntent();
// if (in != null)
// {
// byte[] bis = in.getByteArrayExtra("bitmap");
// bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
// }
//
// preview = (ImageView) this.findViewById(R.id.preview);
//
// if(bitmap == null)
// {
// Log.e("11","bitmap is NULL !");
// }
// else
// {
// preview.setImageBitmap(bitmap);
// }
}


}


<?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:orientation="vertical" >
    <LinearLayout 
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="match_parent"
        >
        <Button 
        android:id="@+id/btngopicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="go picture"
        android:padding="10dp"
        />
    <Button 
        android:id="@+id/btngocamer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="go camer"
        android:padding="10dp"
        />
    <TextView 
        android:id="@+id/tvback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="back"
        android:background="#f5f5f5"
        />
        
    </LinearLayout>
    
    


</LinearLayout>



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:id="@+id/relaview"
    >


    <ImageView
        android:id="@+id/src_pic"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:scaleType="matrix" 
       />


    <com.test.www.ClipView
        android:id="@+id/clipview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />


    <Button
        android:id="@+id/sure"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="裁剪" />
    <Button
        android:id="@+id/xuanz"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="旋转" />


</RelativeLayout>




<?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:orientation="vertical" >


    <ImageView
        android:id="@+id/preview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</LinearLayout>




  <!-- SDCard中创建与删除文件权限 -->  
  <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
 <!-- 向SDCard写入数据权限 -->  
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值