您的位置:首页 > 移动开发 > Android开发

简单实用的android 图片的压缩

2016-04-28 13:46 507 查看
上传图片的时候我们经常因为图片太大问题要进行压缩图片的;本例子通过拍照得到一张图片来进行压缩展示的

直接贴代码了(因为都比较简单,注释的话很清楚,主要的操作还是在最后一步):

首先看下工具类
<span style="font-size:14px;">package com.example.compressphoto;

import java.io.ByteArrayOutputStream;
import java.io.File;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.util.Base64;

public class PictureUtil {

/**
* 把bitmap转换成String
*
* @param filePath
* @return
*/
public static String bitmapToString(String filePath) {

Bitmap bm = getSmallBitmap(filePath);

ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
byte[] b = baos.toByteArray();

return Base64.encodeToString(b, Base64.DEFAULT);

}

/**
* 计算图片的缩放值
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}

/**
* 根据路径获得突破并压缩返回bitmap用于显示
*
* @param imagesrc
* @return
*/
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);

// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);

// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;

return BitmapFactory.decodeFile(filePath, options);
}

/**
* 根据路径删除图片
*
* @param path
*/
public static void deleteTempFile(String path) {
File file = new File(path);
if (file.exists()) {
file.delete();
}
}

/**
* 添加到图库
*/
public static void galleryAddPic(Context context, String path) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(path);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
context.sendBroadcast(mediaScanIntent);
}

/**
* 获取保存图片的目录
*
* @return
*/
public static File getAlbumDir() {
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
getAlbumName());
if (!dir.exists()) {
dir.mkdirs();
}
return dir;
}

/**
* 获取 保存图片文件夹名称
*
* @return
*/
public static String getAlbumName() {
return "picture";
}
}</span>


首先是调用拍照

<span style="font-size:14px;">/**
* 拍照*/
public void takephono(View view){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
// 指定存放拍摄照片的位置
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
e.printStackTrace();
}
}</span>


<span style="font-size:14px;">/**
* 把程序拍摄的照片放到 SD卡的 Pictures目录中 picture 文件夹中
* 照片的命名规则为:wzy_20160428_173729.jpg
*
* @return
* @throws IOException
*/
@SuppressLint("SimpleDateFormat")
private File createImageFile() throws IOException {

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timeStamp = format.format(new Date());
String imageFileName = "wzy_" + timeStamp + ".jpg";

File image = new File(PictureUtil.getAlbumDir(), imageFileName);

mCurrentPhotoPath = image.getAbsolutePath();
return image;
}</span>




再是对拍照返回的操作

<span style="font-size:14px;">@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO) {
if (resultCode == Activity.RESULT_OK) {
// 添加到图库,这样可以在手机的图库程序中看到程序拍摄的照片
PictureUtil.galleryAddPic(this, mCurrentPhotoPath);
againImage.setImageBitmap(BitmapFactory.decodeFile(mCurrentPhotoPath));//不知道为啥就是显示不出来
} else {

// 取消照相后,删除已经创建的临时文件。
PictureUtil.deleteTempFile(mCurrentPhotoPath);
mCurrentPhotoPath =null;
}
}
}</span>


然后就是我们关注的压缩的操作(给压缩之后的图片创建一个新的文件,所以我们上传服务器的文件路径就得用这个了)

<span style="font-size:14px;">/**
* 压缩
* (多文件压缩使用循环的方法就,可以了)
* */
public void compressPhoto(View view){
if (mCurrentPhotoPath != null) {
try {

File f = new File(mCurrentPhotoPath);
Bitmap bm = PictureUtil.getSmallBitmap(mCurrentPhotoPath);
//新的压缩之后的图片的路径是“原路径,只不过在名字之前加了一个small_”
FileOutputStream fos = new FileOutputStream(new File(PictureUtil.getAlbumDir(), "small_" + f.getName()));
bm.compress(Bitmap.CompressFormat.JPEG, 40, fos);//这里压缩40%,把压缩后的数据存放到fos中

nowImage.setImageBitmap(PictureUtil.getSmallBitmap(PictureUtil.getAlbumDir()+"/"+"small_" + f.getName()));
Log.i("原始文件的大小", f.length()+"");
Log.i("压缩后文件的大小",new File(PictureUtil.getAlbumDir(), "small_" + f.getName()).length()+"");

} catch (Exception e) {
e.printStackTrace();
}

} else {
Toast.makeText(this, "请先点击拍照按钮拍摄照片", Toast.LENGTH_SHORT).show();
}
}</span>


最后demo下载链接http://www.oschina.net/code/snippet_2702417_55777
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: