• Android实现图片裁剪




    MainActivity.java

    package com.kale.imagetailor;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    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.drawable.BitmapDrawable;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity {
    	
    	private String tag = getClass().getSimpleName();
    	private static Uri imageUri;
    	
    	Button imageTailorBt;
    	ImageView userIV;
    	File file;
    	FileManager fm;
    	
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    		viewInit();
    		fm = new FileManager();
    		try {
    			file = fm.creatSDFile("Kale Image", "userImage.jpg");
    		} catch (IOException e) {
    			// TODO 自动生成的 catch 块
    			e.printStackTrace();
    		}
    	}
    	
    	/**
    	 *每次开启时判断设置什么图片,如果有自定义的图片了,那么就用用户自己的头像 
    	 */
    	private void setUserImage(){
    		userIV.setImageResource(R.drawable.ic_launcher);  
    		//从sd卡中得到图片资源
            String filepath = fm.getFileWholePath();
            Bitmap bm = BitmapFactory.decodeFile(filepath);
    
            if(bm != null){
            	//BtimapDrawable是Drawable的子类,最终直接使用bd对象即可。
            	userIV.setImageDrawable(new BitmapDrawable(bm));
            }
            else{
            	userIV.setImageResource(R.drawable.ic_launcher); 
            }
    	}
    	
    	private void viewInit(){
    		userIV = (ImageView)findViewById(R.id.user_imageView_id);
    		imageTailorBt = (Button)findViewById(R.id.image_tailer_button_id);
    		imageTailorBt.setOnClickListener(new OnClickListener() {
    			
    			@Override
    			public void onClick(View arg0) {
    				// TODO 自动生成的方法存根
    				changeUserImage();
    			}
    		});
    	}
    	
    	
    	/**
    	 *改变用户头像的方法,这里设定一个intent交给activity去处理
    	 */
    	protected void changeUserImage(){
    		Toast.makeText(getApplicationContext(), "更换头像", 0).show();
    		imageUri = Uri.parse("file:///sdcard/temp.jpg"); 
    		
    		Intent intent = null;
    		intent = new Intent(Intent.ACTION_GET_CONTENT, null);
    		intent.setType("image/*");// 设置属性,表示获取任意类型的图片
    		intent.putExtra("crop", "true");// 设置可以滑动选选择区域的属性,注意这里是字符串"true" 
    		intent.putExtra("aspectX", 1);// 设置剪切框1:1比例的效果  
    		intent.putExtra("aspectY", 1);// 设置剪切框1:1比例的效果  
    		intent.putExtra("outputX", 600);
    		intent.putExtra("outputY", 600);
    		intent.putExtra("scale", true);
    		intent.putExtra("return-data", false);
    		intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
    		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    		intent.putExtra("noFaceDetection", false); // no face detection
    		startActivityForResult(intent, 1);
    	}
    	
    	/**
    	 * @param uri
    	 * @return 一个bitmap对象,用来设置图片
    	 */
    	private Bitmap decodeUriAsBitmap(Uri uri){
    		Bitmap bitmap = null;
    		try {
    			bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    			return null;
    		}
    		return bitmap;
    	}
    	
    	/**
    	 * 用来设置图片,并保持的本地
    	 */
    	@Override
    	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    		super.onActivityResult(requestCode, resultCode, data);
    		//不正确的情况下
    		if(resultCode != Activity.RESULT_OK){
    			Log.e(tag, "requestCode = " + requestCode);
    			Log.e(tag, "resultCode = " + resultCode);
    			Log.e(tag, "data = " + data);
    			return;
    		}
    		else{
    			Log.d(tag, "CHOOSE_A_BIG_PICTURE: data = " + data);
    			if(imageUri != null){
    				Bitmap photo = decodeUriAsBitmap(imageUri);
    				try {
    					//保存到本地文件
    					File pictureFile = file;
    					FileOutputStream fos = new FileOutputStream(pictureFile);
    					photo.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    			        fos.close();
    			        Toast.makeText(this, "设置成功~", 0).show();
    			       
    				} catch (FileNotFoundException e) {
    					e.printStackTrace();
    					Toast.makeText(this, "保存路径不存在", 0).show();
    				} catch (IOException e) {
    					e.printStackTrace();
    					Toast.makeText(this, "设置图片失败", 0).show();
    				}
    			}
    		}
    		setUserImage();
    	}
    }
    

    FileManager.java

    package com.kale.imagetailor;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import android.os.Environment;
    
    /**
     * @tips  :
     *  <!-- 读写SD卡的权限 -->
        <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
     * @date  :2014-6-30
     */
    public class FileManager {
    	private String SD_PATH;
    	private String fileName;
    	private String dirName;
    
    	public String getSD_PATH() {
    		return SD_PATH;
    	}
    	public FileManager() {
    		//得到当前外部存储设备的目录
    		SD_PATH = Environment.getExternalStorageDirectory() + "/";
    	}
    	/**
    	 * 在SD卡上创建文件
    	 * 
    	 * @throws IOException
    	 */
    	public File creatSDFile(String dirName ,String fileName) throws IOException {
    		this.fileName = fileName;
    		this.dirName = dirName;
    		File file = new File(creatSDDir(dirName), fileName);
    		return file;
    	}
    	
    	
    	public String getFileWholePath(){
    		return SD_PATH + dirName + "/" + fileName;
    	}
    	
    	/**
    	 * 在SD卡上创建目录
    	 * 
    	 * @param dirName
    	 */
    	public File creatSDDir(String dirName) {
    		File dir = new File(SD_PATH + dirName);
    		dir.mkdir();
    		return dir;
    	}
    	
    
    
    	/**
    	 * 判断SD卡上的文件夹是否存在
    	 */
    	public boolean isFileExist(String fileName ,String dirName){
    		File file = new File(SD_PATH +dirName+"/"+ fileName);
    		return file.exists();
    	}
    	
    	/**
    	 * 将一个InputStream里面的数据写入到SD卡中
    	 */
    	public File saveToSdCard(String dirName,String fileName,InputStream input){
    		File file = null;
    		OutputStream output = null;
    		try{
    			//创建目录
    			creatSDDir(dirName);
    			//建立文件
    			file = creatSDFile(dirName ,fileName);
    			output = new FileOutputStream(file);
    			byte buffer [] = new byte[5 * 1024];
    			int count = 0;
    			while((count = input.read(buffer)) != -1){
    				String str = new String(buffer,0,count);
    				//str = new String(str.getBytes("iso-8859-1"),"utf-8");				
    				System.out.println("---------File Manager----start--------");
    				System.out.println(str);
    				System.out.println("---------File Manager-----end-------");
    				output.write(buffer);
    			}
    			output.flush();
    		}
    		catch(Exception e){
    			e.printStackTrace();
    		}
    		finally{
    			try{
    				output.close();
    			}
    			catch(Exception e){
    				e.printStackTrace();
    			}
    		}
    		return file;
    	}
    
    }


    main_activity.xml
    <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}" >
    
        <Button
            android:id="@+id/image_tailer_button_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="裁剪图片" />
    
        <ImageView
            android:id="@+id/user_imageView_id"
            android:layout_width="300dp"
            android:layout_height="300dp"
            android:layout_above="@+id/image_tailer_button_id"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="100dp"
            android:src="@drawable/ic_launcher" />
    
    </RelativeLayout>
    

    代码:http://download.csdn.net/detail/shark0017/7623057
  • 相关阅读:
    About unsign in Java
    Heart Shape Function
    Java内存分配与垃圾回收的关系
    Android Volume Button Listener
    Android Opensource Lib
    Android Lock Screen Orientation
    JS moveStart和moveEnd方法(TextRange对象查找与选择)
    一个简单的遮罩层效果
    IE中的条件注释(<![if lt IE 7]><![endif]>)
    document.execCommand()用法说明
  • 原文地址:https://www.cnblogs.com/tianzhijiexian/p/3852653.html
Copyright © 2020-2023  润新知