Android 照相机拍摄照片,压缩后储存于SD卡

来源:互联网 发布:中国历年农民工数据 编辑:程序博客网 时间:2024/05/04 05:40

作者 : 卿笃军

原文地址:http://blog.csdn.net/qingdujun/article/details/39480117


一般相机拍摄的照片大小为3-4M左右,这里因为需要完成将拍摄好的照片上传到服务器功能,所以需要将得到的照片进行压缩。这里演示就直接存放在SD卡中。

网上搜索了不少资料,得知可以使用:inSampleSize 设置图片的缩放比例。

但是,这里需要注意:

1)inJustDecodeBounds = true; 需要先设置为真,表示只获得图片的资料信息。如果此时检验bitmap会发现bitmap==null;

2)如果需要加载图片的时候,必须重新设置inJustDecodeBounds = false;

一、实现图片压缩(网上看到别人的,自己稍微修改了一下):

//压缩图片尺寸    public Bitmap compressBySize(String pathName, int targetWidth,              int targetHeight) {          BitmapFactory.Options opts = new BitmapFactory.Options();          opts.inJustDecodeBounds = true;// 不去真的解析图片,只是获取图片的头部信息,包含宽高等;          Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);        // 得到图片的宽度、高度;          float imgWidth = opts.outWidth;          float imgHeight = opts.outHeight;          // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数;          int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);          int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);         opts.inSampleSize = 1;        if (widthRatio > 1 || widthRatio > 1) {              if (widthRatio > heightRatio) {                  opts.inSampleSize = widthRatio;              } else {                  opts.inSampleSize = heightRatio;              }          }          //设置好缩放比例后,加载图片进内容;          opts.inJustDecodeBounds = false;          bitmap = BitmapFactory.decodeFile(pathName, opts);          return bitmap;      }
二、将压缩后的图片存储于SD卡:

//存储进SD卡    public void saveFile(Bitmap bm, String fileName) throws Exception {        File dirFile = new File(fileName);          //检测图片是否存在        if(dirFile.exists()){              dirFile.delete();  //删除原图片        }          File myCaptureFile = new File(fileName);          BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));          //100表示不进行压缩,70表示压缩率为30%        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);          bos.flush();          bos.close();      }  
这里注意,由于需要写SD卡,要添加一个权限:

<!-- 写SD卡 -->    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
三、附上一个完整的小Demo:

1)MainActivity.java

package com.face.sendwinrar;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileOutputStream;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;public class MainActivity extends Activity {//照片保存地址private static final String FILE_PATH = "/sdcard/gone.jpg";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        try {         //压缩图片        Bitmap bitmap = compressBySize(FILE_PATH,150,200);        //保存图片        saveFile(bitmap, FILE_PATH);        } catch (Exception e) {e.printStackTrace();}         }        //压缩图片尺寸    public Bitmap compressBySize(String pathName, int targetWidth,              int targetHeight) {          BitmapFactory.Options opts = new BitmapFactory.Options();          opts.inJustDecodeBounds = true;// 不去真的解析图片,只是获取图片的头部信息,包含宽高等;          Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);        // 得到图片的宽度、高度;          float imgWidth = opts.outWidth;          float imgHeight = opts.outHeight;          // 分别计算图片宽度、高度与目标宽度、高度的比例;取大于等于该比例的最小整数;          int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);          int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);         opts.inSampleSize = 1;        if (widthRatio > 1 || widthRatio > 1) {              if (widthRatio > heightRatio) {                  opts.inSampleSize = widthRatio;              } else {                  opts.inSampleSize = heightRatio;              }          }          //设置好缩放比例后,加载图片进内容;          opts.inJustDecodeBounds = false;          bitmap = BitmapFactory.decodeFile(pathName, opts);          return bitmap;      }    //存储进SD卡    public void saveFile(Bitmap bm, String fileName) throws Exception {        File dirFile = new File(fileName);          //检测图片是否存在        if(dirFile.exists()){              dirFile.delete();  //删除原图片        }          File myCaptureFile = new File(fileName);          BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));          //100表示不进行压缩,70表示压缩率为30%        bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);          bos.flush();          bos.close();      }      @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }}
2)mainfest

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.dc.xust.paybyface"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="15" />    <!-- 写SD卡 -->    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>
这里直接运行就OK 了,不需要界面,main_activity.xml文件直接就是默认的,这里就不附上来了。


参考文献:几天前的网页,现在找不到了,找到了就添上来。

原文地址:http://blog.csdn.net/qingdujun/article/details/39480117


3 0
原创粉丝点击