压缩图片的工具类

package com.rjgrid.gaojiaosns.img.util;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


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;
import android.util.Log;

/** 
 * 
 * TODO 处理图片压缩的工具类
 */
public class PictureUtils {
	private final static int compressVal=75;
	/**
	  * 把bitmap转换成String
	  * 将图片保存到本地
	  * @param filePath
	  * @return
	  */
	 public static String bitmapToString(Bitmap bitmap) {
		   ByteArrayOutputStream baos = new ByteArrayOutputStream();
		   bitmap.compress(Bitmap.CompressFormat.JPEG, compressVal, baos);
		   
		   byte[] b = baos.toByteArray();
		   return Base64.encodeToString(b, Base64.DEFAULT);
		 }
	
	 /**
	  * 计算图片的缩放值
	  * 如果图片的原始高度或者宽度大与我们期望的宽度和高度,我们需要计算出缩放比例的数值。否则就不缩放。
	  * heightRatio是图片原始高度与压缩后高度的倍数,
	  * widthRatio是图片原始宽度与压缩后宽度的倍数。
	  * inSampleSize就是缩放值 ,取heightRatio与widthRatio中最小的值。
	  * inSampleSize为1表示宽度和高度不缩放,为2表示压缩后的宽度与高度为原来的1/2(图片为原1/4)。
	  * @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,int w,int h) {
		   final BitmapFactory.Options options = new BitmapFactory.Options();
		   
		   //该值设为true那么将不返回实际的bitmap不给其分配内存空间而里面只包括一些解码边界信息即图片大小信息
		   options.inJustDecodeBounds = true;//inJustDecodeBounds设置为true,可以不把图片读到内存中,但依然可以计算出图片的大小
		   BitmapFactory.decodeFile(filePath, options);
		
		   // Calculate inSampleSize
		   options.inSampleSize = calculateInSampleSize(options, w, h);
		
		   // Decode bitmap with inSampleSize set
		   options.inJustDecodeBounds = false;//重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false
		   Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);// BitmapFactory.decodeFile()按指定大小取得图片缩略图
		   
		   return bitmap;
		 }
	
	 /**
	  * 保存到本地
	  * @param bitmap
	  */
	 public static boolean saveBitmap(Bitmap bitmap,String savePath){
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			File file = new File(savePath);
			try {
				file.createNewFile();
				BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(file));

				bitmap.compress(Bitmap.CompressFormat.JPEG, compressVal, baos);
				os.write(baos.toByteArray());

				os.flush();
				os.close();
				
			} catch (IOException e) {
				Log.d("BITMAP", e.getMessage());
			} finally {
				if (bitmap != null) {
					bitmap.recycle();
				}
			}
			return true;
		 }
	 
	 /***
	 * 根据路径删除图片
     * @param path
     * @return
     * @throws IOException
     */
    public static boolean deleteTempFile(String path)throws IOException{
        boolean isOk=true;
        File file = new File(path);
        if(file!=null){
            if(file.exists()){
                if(!file.delete()){
                    isOk=false;
                }
            }
        }
        return isOk;
    }
    
    /***
     * 获取文件扩展名
     * @param filename
     * @return 返回文件扩展名
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }
    

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android图片压缩工具类是一种用于压缩Android应用中的图片文件的工具。根据引用和引用的内容,这个工具类的具体实现可能包括以下功能: - 通过将图片文件转换为字节数组,以便进行后续的压缩处理。 - 使用缓冲输出流将压缩后的图片数据写入输出流中。 - 通过设置合适的压缩参数,对图片进行压缩操作,减小文件大小但尽量保持良好的图像质量。 - 可能还包括一些其他的图像处理操作,如旋转、裁剪等。 具体的实现细节可以参考引用和引用提供的代码示例。在这些示例中,使用了ByteArrayInputStream和ByteArrayOutputStream类来处理字节数组的输入和输出。通过设置合适的压缩参数,可以实现对图片压缩操作。此外,还可以使用BufferedOutputStream类来提高输出流的写入性能。 如果想要进一步了解关于Android图片压缩工具类的使用和实现细节,可以参考引用提供的配套资料,该资料可能提供了更详细的解释和示例代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Android开发之图片压缩工具类完整实例](https://download.csdn.net/download/weixin_38517904/14018839)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [android图片压缩工具类分享](https://download.csdn.net/download/weixin_38616330/14881444)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Spring Boot(六十四):SpringBoot集成Gzip压缩数据](https://download.csdn.net/download/u013938578/88221156)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值