bitmapとfileの間に変換して使用する

9379 ワード

1.bitmapとfileの間で変換して使用する
2.サムスンの携帯で写真を撮る時、写真は反対で、設定します.
package com.finstone.face;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;

/**
 *   bitmap     
 * @author    
 *
 */
public class BitmapFileSetting {
	
	/**
	 *       
	 *          
	 * @param filePath
	 * @throws IOException 
	 */
	public static File samsungPhoneSetting(String filePath) throws IOException{
		
		//             
		int bitmapDegree = getBitmapDegree(filePath);
		//       bitmap
		Bitmap bitMBitmap;
		bitMBitmap = decodeFile(filePath);
		if (bitMBitmap == null){
			return null;
		}
		//    bitmap
		Bitmap rotateBitmapByDegree = rotateBitmapByDegree(bitMBitmap, bitmapDegree);
		File saveBitmapFile = saveBitmapFile(rotateBitmapByDegree, filePath);
		return saveBitmapFile;
	}
	
	/**
	 * uri   File
	 * @param uri
	 * @return
	 */
	public File uriTurnFile(Uri uri, Activity activity){
		
		if(uri == null){
			return null;
		}
		
		File file = null;  
        String[] proj = { MediaStore.Images.Media.DATA };  
        Cursor actualimagecursor = activity.managedQuery(uri, proj, null,  
                null, null);  
        int actual_image_column_index = actualimagecursor  
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
        actualimagecursor.moveToFirst();  
        String img_path = actualimagecursor  
                .getString(actual_image_column_index);  
        file = new File(img_path);  
        return file;  
	}
	
	/**
	 *       bitmap
	 * @param urlpath
	 * @return
	 */
	public static Bitmap getBitMBitmap(String urlpath) {  
		
		 Bitmap map = null;  
		 try {  
			  URL url = new URL(urlpath);  
			  URLConnection conn = url.openConnection();  
			  conn.connect();  
			  InputStream in;  
			  in = conn.getInputStream();  
			  map = BitmapFactory.decodeStream(in);  
			 // TODO Auto-generated catch block  
		  } catch (IOException e) {  
			  e.printStackTrace();  
		 }  
		return map;  
	}  
	
	/**
	 *  batmap  file
	 * @param bitmap
	 * @param filepath
	 */
	public static File saveBitmapFile(Bitmap bitmap, String filepath){ 
		File file=new File(filepath);//          
		try { 
			BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); 
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
			bos.flush(); 
			bos.close(); 
		} catch (IOException e) { 
			e.printStackTrace(); 
		} 
		return file;
	}
	
	/**
     *           
     *
     * @param path       
     * @return        
	 * @throws IOException 
     */
    public static int getBitmapDegree(String path) throws IOException {
        int degree = 0;
        //           ,    EXIF  
        ExifInterface exifInterface = new ExifInterface(path);
        //          
        int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL);
        switch (orientation) {
            case ExifInterface.ORIENTATION_ROTATE_90:
                degree = 90;
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                degree = 180;
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                degree = 270;
                break;
        }
       
        return degree;
    }
    
    /**
     *              
     *
     * @param bm            
     * @param degree     
     * @return       
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;
 
        //       ,      
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
      
        //                ,       
        returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
       
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }
    
    /**
     *          file    bitmap
     * @param filePath
     * @return
     * @throws IOException
     */
    public static Bitmap decodeFile(String filePath) throws IOException{
        Bitmap b = null;
        int IMAGE_MAX_SIZE = 600;
      
    	File f = new File(filePath);
    	if (f == null){
    		return null;
    	}
        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        FileInputStream fis = new FileInputStream(f);
        BitmapFactory.decodeStream(fis, null, o);
        fis.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        fis = new FileInputStream(f);
        b = BitmapFactory.decodeStream(fis, null, o2);
        fis.close();
        return b;
    }
}
3.システム自体のカメラ機能、方法を呼び出します.
package com.finstone.face;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.finstone.utils.PreferencesUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.Toast;

/**
 *           
 * @author yuhaifei
 *
 */
@SuppressLint("NewApi")
public class CameraSystem {
	
	/**
	 * 
	 * @author yuhaifei
	 */
	public static enum OFTENTYPE {
	   
	    BEFORECAMERA,//    
	    BEHINDCAMERA,
	    CAMERA_ACTIVITY,  //      
	    ALIPAY
	}
	
	private static final String FILE_PATH = "/sdcard/syscamera.jpg";
	
	private Context context;//    
	private Activity activity;//    
	private Fragment fragment;//    
	private  String string_Data;//     activity      (        ),       
	public void setString_Data(String string_Data) {
		
		//      
		PreferencesUtil.setSharedStringData(context, "IdCard", string_Data);
		this.string_Data = string_Data;
	}
	
	public String getString_Data() {
		
		//        
		String sharedStringData = PreferencesUtil.getSharedStringData(context, "IdCard");
		return sharedStringData;
	}
	
	public CameraSystem() {
		
	}
	
	/**
	 *        
	 * @param context
	 * @param activity
	 */
	public CameraSystem(Context context,Activity activity) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.activity = activity;
	
		this.upCameraSystem(activity,null);
	}
	
	public CameraSystem(Context context,Fragment fragment) {
		// TODO Auto-generated constructor stub
		this.context = context;
		this.fragment = fragment;
	
		this.upCameraSystem(null,fragment);
	}
	
	/**
	 *        
	 */
	private void upCameraSystem(Activity activity,Fragment fragment){
		
		Intent intent = new Intent();
		//          Action
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
	
		if (!Build.BRAND.equals("samsung")){
			
			//         OFTENTYPE.BEFORECAMERA.ordinal()
			intent.putExtra("android.intent.extras.CAMERA_FACING", 1); 
		}
		else {
			//         OFTENTYPE.BEFORECAMERA.ordinal()
			intent.putExtra("android.intent.extras.CAMERA_FACING", 0); 
		}
		
		//intent.putExtra("android.intent.extras.CAMERA_FACING_FRONT", 1); 
		//FindFrontCamera();
		intent.addCategory(Intent.CATEGORY_DEFAULT);
		//           
		File file = new File(FILE_PATH);
		if (file.exists()) {
			file.delete();
		}
		
		//         Uri  
		Uri uri = Uri.fromFile(file);
		//                       
		intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		if (activity != null){
			activity.startActivityForResult(intent, OFTENTYPE.CAMERA_ACTIVITY.ordinal());
		}
		else {
			fragment.startActivityForResult(intent, OFTENTYPE.CAMERA_ACTIVITY.ordinal());
		}	
	}
	
	/**
	 *     
	 */
	public File closeCameraSystem(int requestCode){
		File file = null;
		if (requestCode == OFTENTYPE.CAMERA_ACTIVITY.ordinal()){
			
			//        
			if (!Build.BRAND.equals("samsung")){
				file = new File(FILE_PATH);
			}
			
			try {
				file = BitmapFileSetting.samsungPhoneSetting(FILE_PATH);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				//Toast.makeText(context, "       ", Toast.LENGTH_LONG).show();
				return null;
			}
		}
		
		return file;
	}
}