Android JAVA 裁剪、压缩图片

          ***********************************************************************************************************************************************************************************

    前一段时间项目进入维护阶段之后,工作也不是很忙,不过没清闲几天,Boss就找我有任务了,让把项目中图片文件夹中的图片循环遍历,并判断,如果图片不是方形的,先裁剪成方形的;然后,判断图片大于300kb的话,压缩到300kb。

    想了一下,也不需要界面,直接创建java工程,在main里面实现就可以了。

    直接贴代码了:

    a.遍历图片文件夹:

     static void showAllFiles(String path) {
		File root = null;
		try {
			root = new File(path);
			if (root.exists()) {  //D:/test/temp
				File[] files = root.listFiles();  //三个文件夹
				if (files.length == 0) {
					System.out.println("文件夹是空的!");
					return;
				} else {
					//遍历图片文件夹
					for (File file : files) {
						if (file.isDirectory()) {
							//文件夹里面含有子文件夹
							showAllFiles(file.getAbsolutePath());
							// 得到该指定目录下的所有文件
						} else {
							//文件夹里面不含有子文件夹
							/*
							 * System.out.println("显示"+filePath+"下所有子目录"+file.
							 * getAbsolutePath());
							 */
							String filePath = ""; // 文件夹下单个文件的路径
							String filePicName = ""; // 文件名称
							String pictureFormat = "";// 图片的格式

							getImgInfo(file.getPath());   
							
						}
					}
				}
			} else {
				System.out.println("文件不存在!");
			}
		} catch (Exception e) {
			System.out.println(e.toString()); // 空指针
		}
	}

            b.判断图片形状  

    判断图片形状的依据就是图片的话宽和高,所以只要获取到图片的width和height,那就很容易判断了。而java又为我们提供了一个使用很方便的图片类BufferedImage ,通过ImageIO.read(File)就可以获取。

      <span style="font-family:KaiTi_GB2312;"> </span><span style="font-family:SimSun;">public static void getImgInfo(String imgpath) { 
    	String fileName = null;   //图片文件名称
    	String format = null ;   //图片转换格式
    	String tempFilePath = "" ;  //临时文件路径
    	String destFilePath = "" ;  //目标文件夹的路径
    	File tempFile = null ;
    	String temp[] = imgpath.replaceAll("\\\\", "/").split("/");
    	//获取图片名称
    	if (temp.length > 1) {
			fileName = temp[temp.length-1];
		}
    	format = fileName.substring(fileName.lastIndexOf(".")).replace(".", "");
    	if ("jpg".equals(format)||"JPG".equals(format)) {
    		format = "JPG";
		} else if ("png".equals(format)||"PNG".equals(format)){
			format = "PNG";
		}else if ("bmp".equals(format)||"BMP".equals(format)){
			format = "BMP";
		}
    	for (int i = 0; i < temp.length; i++) {
    		if (i >1&&i<temp.length-1) {
    			tempFile =new File("D://dest//"+tempFilePath + temp[i]); 
    			//如果文件夹不存在则创建    
    			if  (!tempFile .exists()  && !tempFile .isDirectory())      
    			{       
    				tempFile .mkdir();    
    			} else{  
    			    System.out.println("//目录存在");  
    			}  
    			tempFilePath =tempFilePath + temp[i]+"//";
			}
    		if (i == temp.length-1) {
    			destFilePath = tempFile.getAbsolutePath()+"\\"+fileName;
    		}
		}
            File imgfile = new File(imgpath); 
            int size = 0 ;
            try { 
                    FileInputStream fis = new FileInputStream(imgfile);  //将文件转化为文件输入流
                    FileOutputStream fos = new FileOutputStream(destFilePath); //创建文件输出流
                    BufferedImage bufferedImage = ImageIO.read(imgfile); 
                    if (fis.available()==0) {
						return ;
					}
                    //判断图片形状
                    if (bufferedImage.getWidth()>bufferedImage.getHeight()&&fis.available()/1024-300>0) {
						size = bufferedImage.getHeight() ;
					} else if(bufferedImage.getWidth()>bufferedImage.getHeight()&&fis.available()/1024-300<0){
						size = bufferedImage.getHeight() ;
					}else if(bufferedImage.getWidth()==bufferedImage.getHeight()&&fis.available()/1024-300>0){
						size = bufferedImage.getHeight() ;
					}else if(bufferedImage.getWidth()==bufferedImage.getHeight()&&fis.available()/1024-300<=0){
						size = bufferedImage.getHeight() ;
					}else if(bufferedImage.getWidth()<bufferedImage.getHeight()&&fis.available()/1024-300==0){
						size = bufferedImage.getWidth() ;
					}else if(bufferedImage.getWidth()<bufferedImage.getHeight()&&fis.available()/1024-300>0){
						size = bufferedImage.getWidth() ;
					}else if(bufferedImage.getWidth()>bufferedImage.getHeight()&&fis.available()/1024-300==0){
						size = bufferedImage.getHeight() ;
					}else if(bufferedImage.getWidth()<bufferedImage.getHeight()&&fis.available()/1024-300<0){
						size = bufferedImage.getWidth() ;
					}
                    resizeImage(fis, fos, size, format);
                    
            } catch (FileNotFoundException e) { 
                   /* System.err.println("所给的图片文件" + .getPath() + "不存在!计算图片尺寸大小信息失败!"); */
                      
            } catch (IOException e) { 
                    System.err.println("计算图片" + imgfile.getPath() + "尺寸大小信息失败!"); 
            } 
    } </span>

          c.裁剪、等比例压缩        

    在调试的过程中,发现,由于图片的形状和规定的基本上都不一样,但是如果不在需求300kb的图片,如果裁剪之后,也就会变的符合要求,而如果是方形的图片,压缩之后,也不会影响图片的形状,所以,就用这一个方法一块实现了。

    最后将设定好的width、height再次创建BufferedImage,将image对象传入Graphics类,绘制出新的图形,通过ImageIO输出到指定位置即可。

       /** 
	* 改变图片的大小到宽为size,然后高随着宽等比例变化 
	* @param is 上传的图片的输入流 
	* @param os 改变了图片的大小后,把图片的流输出到目标OutputStream 
	* @param size 新图片的宽 
	* @param format 新图片的格式 
	* @throws IOException 
	*/ 
	public static void resizeImage(FileInputStream is, FileOutputStream os, int size, String format) throws IOException { 
	BufferedImage prevImage = ImageIO.read(is); 
	double width = prevImage.getWidth(); 
	double height = prevImage.getHeight(); 
	double percent ;
	int newWidth ,newHeight;
	//宽大于高  传进来的size为小值
	if (width>=height) {
		percent = size/width; 
		newWidth = (int)(width * percent); 
		newHeight = (int) height; 
	} else {
		//宽小于高
		percent = size/height;
		newWidth = (int)width; 
		newHeight = (int) (height * percent);
	}
	BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_BGR); // <span style="font-family: Arial, Helvetica, sans-serif;">BufferedImage.TYPE_INT_BGR 表示<span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">表示一个具有 8 位            </span><span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; line-height: 24px; background-color: rgb(245, 245, 245);"><span style="font-size:10px;">RGB 颜色分量的图像,对应于 Windows 或 Solaris 风格的 BGR 颜色模型,具有打包为整数像素的 Blue、Green 和 Red 三种颜色。</span></span></span><span style="line-height: 24px; color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif;font-size:10px;">      </span>
<span style="font-family:Helvetica, Tahoma, Arial, sans-serif;font-size:10px;color:#333333;"><span style="line-height: 24px;"></span></span><pre name="code" class="java">       // Graphics 为绘制图形的类,和Android自定义中的canvas作用类似
Graphics graphics = image.createGraphics(); graphics.drawImage(prevImage, 0, 0, newWidth, newHeight, null); ImageIO.write(image, format, os); os.flush(); is.close(); os.close(); }

 

    ***********************************************************************************************************************************************************************************



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值