栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

android图片压缩工具类分享

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

android图片压缩工具类分享

本文实例为大家分享了android图片压缩工具类的具体代码,供大家参考,具体内容如下

import java.io.BufferedOutputStream; 
import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.BitmapFactory.Options; 
import android.graphics.Matrix; 
import android.net.Uri; 
import android.widget.Toast; 
 
 
public class ImageViewTool { 
 
   
  public static Bitmap compressImage(Bitmap image) { 
 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 
    int options = 100; 
    while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 
      baos.reset();// 重置baos即清空baos 
      image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 
      options -= 10;// 每次都减少10 
    } 
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 
    return bitmap; 
  } 
 
   
  public static Bitmap getimage(String srcPath) { 
    BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 
    newOpts.inJustDecodeBounds = true; 
    Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts);// 此时返回bm为空 
 
    newOpts.inJustDecodeBounds = false; 
    int w = newOpts.outWidth; 
    int h = newOpts.outHeight; 
    // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 
    float hh = 800f;// 这里设置高度为800f 
    float ww = 480f;// 这里设置宽度为480f 
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 
    int be = 1;// be=1表示不缩放 
    if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 
      be = (int) (newOpts.outWidth / ww); 
    } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放 
      be = (int) (newOpts.outHeight / hh); 
    } 
    if (be <= 0) 
      be = 1; 
    newOpts.inSampleSize = be;// 设置缩放比例 
    // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 
    bitmap = BitmapFactory.decodeFile(srcPath, newOpts); 
    return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩 
  } 
 
   
  public static Bitmap comp(Bitmap image) { 
 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 
      baos.reset();// 重置baos即清空baos 
      image.compress(Bitmap.CompressFormat.JPEG, 30, baos);// 这里压缩50%,把压缩后的数据存放到baos中 
    } 
    ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); 
    BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 
    newOpts.inJustDecodeBounds = true; 
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); 
    newOpts.inJustDecodeBounds = false; 
    int w = newOpts.outWidth; 
    int h = newOpts.outHeight; 
    // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 
    float hh = 150f;// 这里设置高度为800f 
    float ww = 150f;// 这里设置宽度为480f 
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 
    int be = 1;// be=1表示不缩放 
    if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 
      be = (int) (newOpts.outWidth / ww); 
    } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放 
      be = (int) (newOpts.outHeight / hh); 
    } 
    if (be <= 0) 
      be = 1; 
    newOpts.inSampleSize = be;// 设置缩放比例 
    // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 
    isBm = new ByteArrayInputStream(baos.toByteArray()); 
    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts); 
    return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩 
  } 
 
  public static byte[] Bitmap2Bytes(Bitmap bm) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos); 
    return baos.toByteArray(); 
  } 
 
   
  public static void reducePicture(Context context, Uri inputUri, 
      Uri outputUri, int maxLenth, int compress) { 
    Options options = new Options(); 
    options.inJustDecodeBounds = true; 
    InputStream is = null; 
    try { 
      is = context.getContentResolver().openInputStream(inputUri); 
      BitmapFactory.decodeStream(is, null, options); 
      is.close(); 
      int sampleSize = 1; 
      int longestSide = 0; 
      int longestSideLenth = 0; 
      if (options.outWidth > options.outHeight) { 
 longestSideLenth = options.outWidth; 
 longestSide = 0; 
      } else { 
 longestSideLenth = options.outHeight; 
 longestSide = 1; 
      } 
      if (longestSideLenth > maxLenth) { 
 sampleSize = longestSideLenth / maxLenth; 
      } 
      options.inJustDecodeBounds = false; 
      options.inSampleSize = sampleSize; 
 
      is = context.getContentResolver().openInputStream(inputUri); 
      Bitmap bitmap = BitmapFactory.decodeStream(is, null, options); 
      is.close(); 
 
      if (bitmap == null) { 
 Toast.makeText(context, "图片获取失败,请确认您的存储卡是否正常", 
     Toast.LENGTH_SHORT).show(); 
 return; 
      } 
 
      Bitmap srcBitmap = bitmap; 
      float scale = 0; 
      if (longestSide == 0) { 
 scale = (float) maxLenth / (float) (srcBitmap.getWidth()); 
      } else { 
 scale = (float) maxLenth / (float) (srcBitmap.getHeight()); 
      } 
      Matrix matrix = new Matrix(); 
      matrix.postScale(scale, scale); 
      bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), 
   srcBitmap.getHeight(), matrix, true); 
      // 如果尺寸不变会返回本身,所以需要判断是否是统一引用来确定是否需要回收 
      if (srcBitmap != bitmap) { 
 srcBitmap.recycle(); 
 srcBitmap = null; 
      } 
 
      saveBitmapToUri(bitmap, outputUri, compress); 
      bitmap.recycle(); 
      bitmap = null; 
    } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
  } 
 
  private static boolean saveBitmapToUri(Bitmap bitmap, Uri uri, int compress) 
      throws IOException { 
    File file = new File(uri.getPath()); 
    if (file.exists()) { 
      if (file.delete()) { 
 if (!file.createNewFile()) { 
   return false; 
 } 
      } 
    } 
 
    BufferedOutputStream outStream = new BufferedOutputStream( 
 new FileOutputStream(file)); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, compress, outStream); 
    outStream.flush(); 
    outStream.close(); 
 
    return true; 
  } 
 
} 

接下来看看第二个写法压缩图片的工具类,如下

import java.io.ByteArrayInputStream; 
import java.io.ByteArrayOutputStream; 
import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.sql.Date; 
import java.text.SimpleDateFormat; 
 
import android.graphics.Bitmap; 
import android.graphics.Bitmap.Config; 
import android.graphics.BitmapFactory; 
import android.os.Environment; 
 
 
public class ImageFactory { 
 
   
  public Bitmap getBitmap(String imgPath) { 
    // Get bitmap through image path 
    BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
    newOpts.inJustDecodeBounds = false; 
    newOpts.inPurgeable = true; 
    newOpts.inInputShareable = true; 
    // Do not compress 
    newOpts.inSampleSize = 1; 
    newOpts.inPreferredConfig = Config.RGB_565; 
    return BitmapFactory.decodeFile(imgPath, newOpts); 
  } 
 
   
  public static File compressImage(Bitmap bitmap) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 
    int options = 100; 
    while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩 
      baos.reset();// 重置baos即清空baos 
      options -= 10;// 每次都减少10 
      bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 
      long length = baos.toByteArray().length; 
    } 
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); 
    Date date = new Date(System.currentTimeMillis()); 
    String filename = format.format(date); 
    File file = new File(Environment.getExternalStorageDirectory(), filename + ".png"); 
    try { 
      FileOutputStream fos = new FileOutputStream(file); 
      try { 
 fos.write(baos.toByteArray()); 
 fos.flush(); 
 fos.close(); 
      } catch (IOException e) { 
 
 e.printStackTrace(); 
      } 
    } catch (FileNotFoundException e) { 
 
      e.printStackTrace(); 
    } 
    recycleBitmap(bitmap); 
    return file; 
  } 
 
  public static void recycleBitmap(Bitmap... bitmaps) { 
    if (bitmaps == null) { 
      return; 
    } 
    for (Bitmap bm : bitmaps) { 
      if (null != bm && !bm.isRecycled()) { 
 bm.recycle(); 
      } 
    } 
  } 
 
   
  public void storeImage(Bitmap bitmap, String outPath) throws FileNotFoundException { 
    FileOutputStream os = new FileOutputStream(outPath); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os); 
  } 
 
   
  public Bitmap ratio(String imgPath, float pixelW, float pixelH) { 
    BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true,即只读边不读内容 
    newOpts.inJustDecodeBounds = true; 
    newOpts.inPreferredConfig = Config.RGB_565; 
    // Get bitmap info, but notice that bitmap is null now 
    Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts); 
 
    newOpts.inJustDecodeBounds = false; 
    int w = newOpts.outWidth; 
    int h = newOpts.outHeight; 
    // 想要缩放的目标尺寸 
    float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了 
    float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了 
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 
    int be = 1;// be=1表示不缩放 
    if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 
      be = (int) (newOpts.outWidth / ww); 
    } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放 
      be = (int) (newOpts.outHeight / hh); 
    } 
    if (be <= 0) 
      be = 1; 
    newOpts.inSampleSize = be;// 设置缩放比例 
    // 开始压缩图片,注意此时已经把options.inJustDecodeBounds 设回false了 
    bitmap = BitmapFactory.decodeFile(imgPath, newOpts); 
    // 压缩好比例大小后再进行质量压缩 
    // return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 
    return bitmap; 
  } 
 
   
  public Bitmap ratio(Bitmap image, float pixelW, float pixelH) { 
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    image.compress(Bitmap.CompressFormat.JPEG, 100, os); 
    if (os.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 
      os.reset();// 重置baos即清空baos 
      image.compress(Bitmap.CompressFormat.JPEG, 50, os);// 这里压缩50%,把压缩后的数据存放到baos中 
    } 
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray()); 
    BitmapFactory.Options newOpts = new BitmapFactory.Options(); 
    // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 
    newOpts.inJustDecodeBounds = true; 
    newOpts.inPreferredConfig = Config.RGB_565; 
    Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts); 
    newOpts.inJustDecodeBounds = false; 
    int w = newOpts.outWidth; 
    int h = newOpts.outHeight; 
    float hh = pixelH;// 设置高度为240f时,可以明显看到图片缩小了 
    float ww = pixelW;// 设置宽度为120f,可以明显看到图片缩小了 
    // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 
    int be = 1;// be=1表示不缩放 
    if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放 
      be = (int) (newOpts.outWidth / ww); 
    } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放 
      be = (int) (newOpts.outHeight / hh); 
    } 
    if (be <= 0) 
      be = 1; 
    newOpts.inSampleSize = be;// 设置缩放比例 
    // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 
    is = new ByteArrayInputStream(os.toByteArray()); 
    bitmap = BitmapFactory.decodeStream(is, null, newOpts); 
    // 压缩好比例大小后再进行质量压缩 
    // return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大,反而耗资源,删除 
    return bitmap; 
  } 
 
   
  public void compressAndGenImage(Bitmap image, String outPath, int maxSize) throws IOException { 
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    // scale 
    int options = 100; 
    // Store the bitmap into output stream(no compress) 
    image.compress(Bitmap.CompressFormat.JPEG, options, os); 
    // Compress by loop 
    while (os.toByteArray().length / 1024 > maxSize) { 
      // Clean up os 
      os.reset(); 
      // interval 10 
      options -= 10; 
      image.compress(Bitmap.CompressFormat.JPEG, options, os); 
    } 
 
    // Generate compressed image file 
    FileOutputStream fos = new FileOutputStream(outPath); 
    fos.write(os.toByteArray()); 
    fos.flush(); 
    fos.close(); 
  } 
 
   
  public void compressAndGenImage(String imgPath, String outPath, int maxSize, boolean needsDelete) 
      throws IOException { 
    compressAndGenImage(getBitmap(imgPath), outPath, maxSize); 
 
    // Delete original file 
    if (needsDelete) { 
      File file = new File(imgPath); 
      if (file.exists()) { 
 file.delete(); 
      } 
    } 
  } 
 
   
  public void ratioAndGenThumb(Bitmap image, String outPath, float pixelW, float pixelH) 
      throws FileNotFoundException { 
    Bitmap bitmap = ratio(image, pixelW, pixelH); 
    storeImage(bitmap, outPath); 
  } 
 
   
  public void ratioAndGenThumb(String imgPath, String outPath, float pixelW, float pixelH, boolean needsDelete) 
      throws FileNotFoundException { 
    Bitmap bitmap = ratio(imgPath, pixelW, pixelH); 
    storeImage(bitmap, outPath); 
 
    // Delete original file 
    if (needsDelete) { 
      File file = new File(imgPath); 
      if (file.exists()) { 
 file.delete(); 
      } 
    } 
  } 
 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/156864.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号