最近项目中需要判断上传的图片必须是png,jpg,gif三种格式的图片,并且当图片的宽度大于600px时,压缩图片至600px,并且等比例的压缩图片的高度。

具体的实现形式:

大致的思路是:

  1. 判断根据文件名判断图片的格式是否是png,jpg,gif三种图片文件   定义了 isImageFile 方法
  2. 如果是的,则进入到scaleImage(String imgSrc, String imgDist)方法中判断图片大小,如果图片大小合适,则直接利用copyFile(File fromFile, File toFile)方法复制图片
  3. 在缩放图片中利用到java.awt里面的几个类,并且利用BufferedImage可以加快图片的压缩速度。
package com.ctbri.test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.*; public class PictureChange { static String suffix = ""; public static void main(String[] args) {
String newfilebase = "E:/A_xia_program/image/";
File file = new File(newfilebase + 1);
File[] oldfiles = file.listFiles();
for (File file2 : oldfiles) {
if (isImageFile(file2)) {
if (!scaleImage(newfilebase + 1 + "/" + file2.getName(), newfilebase + 11 + "/" + file2.getName())) {
System.out.println(file2.getName()+"转化成功!");
}
}
}
} public static boolean isImageFile(File file) { String fileName = file.getName(); //获取文件名的后缀,可以将后缀定义为类变量,共后面的函数使用
suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); // 声明图片后缀名数组
if (!suffix.matches("^[(jpg)|(png)|(gif)]+$")) {
System.out.println("请输入png,jpg,gif格式的图片");
return false;
}
return true;
} public static boolean scaleImage(String imgSrc, String imgDist) {
try {
File file = new File(imgSrc);
if (!file.exists()) {
return false;
} InputStream is = new FileInputStream(file);
Image src = ImageIO.read(is);
if (src.getWidth(null) <= 600) {
File tofile = new File(imgDist);
copyFile(file, tofile);
is.close();
return true;
} //获取源文件的宽高
int imageWidth = ((BufferedImage) src).getWidth();
int imageHeight = ((BufferedImage) src).getHeight(); double scale = (double) 600 / imageWidth; //计算等比例压缩之后的狂傲
int newWidth = (int) (imageWidth * scale);
int newHeight = (int) (imageHeight * scale); BufferedImage newImage = scaleImage((BufferedImage) src, scale, newWidth, newHeight); File file_out = new File(imgDist);
ImageIO.write(newImage, suffix, file_out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
} //用于具体的转化
public static BufferedImage scaleImage(BufferedImage bufferedImage, double scale, int width, int height) {
int imageWidth = bufferedImage.getWidth();
int imageHeight = bufferedImage.getHeight();
AffineTransform scaleTransform = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR); return bilinearScaleOp.filter(bufferedImage, new BufferedImage(width, height, bufferedImage.getType()));
} //复制文件
public static void copyFile(File fromFile, File toFile) throws IOException {
FileInputStream ins = new FileInputStream(fromFile);
FileOutputStream out = new FileOutputStream(toFile);
byte[] b = new byte[1024];
int n = 0;
while ((n = ins.read(b)) != -1) {
out.write(b, 0, n);
}
ins.close();
out.close();
}
}

java中判断图片格式并且等比例压缩图片的更多相关文章

  1. JAVA中判断年月日格式是否正确(支持判断闰年的2月份)

    一.先说一下年月日(yyyy-MM-dd)正则表达式: 1.年月日正则表达式:^((19|20)[0-9]{2})-((0?2-((0?[1-9])|([1-2][0-9])))|(0?(1|3|5| ...

  2. java中判断一个字符串是否“都为数字”和“是否包含数字”和“截取数字”

    在javascript中有一个方法isDigit()使用来判断一个字符串是否都是数字,在java的字符串处理方法中没有这样的方法,觉得常常需要用到,于是上网搜了一下,整理出了两个用正则表达式匹配的判断 ...

  3. JSON(三)——java中对于JSON格式数据的解析之json-lib与jackson

    java中对于JSON格式数据的操作,主要是json格式字符串与JavaBean之间的相互转换.java中能够解析JSON格式数据的框架有很多,比如json-lib,jackson,阿里巴巴的fast ...

  4. java中各种时间格式的转化

    http://www.chinaitpower.com/A/2005-01-14/104881.html 使用java.util.Calendar返回间隔天数         static int g ...

  5. (转载)java中判断字符串是否为数字的方法的几种方法

    java中判断字符串是否为数字的方法: 1.用JAVA自带的函数 public static boolean isNumeric(String str){ for (int i = 0; i < ...

  6. 处理页面载入图片js(等比例压缩图片)

    第一页面html  <div class="admin">${answer.content}</div> <div class="admin ...

  7. 等比例压缩图片到指定的KB大小

    基本原理: 取原来的图片,长宽乘以比例,重新生成一张图片,获取这张图片的大小,如果还是超过预期大小,继续在此基础上乘以压缩比例,生成图片,直到达到预期 /** * @获取远程图片的体积大小 单位byt ...

  8. 最新javascript自动按比例显示图片,按比例压缩图片显示

    最新javascript自动按比例显示图片,按比例压缩图片显示 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//E ...

  9. java中判断两个字符串是否相等的问题

    我最近刚学java,今天编程的时候就遇到一个棘手的问题,就是关于判断两个字符串是否相等的问题.在编程中,通常比较两个字符串是否相同的表达式是“==”,但在java中不能这么写.在java中,用的是eq ...

随机推荐

  1. python__new__与__init__的区别

    __new__ __init__区别 1 class A(object): 2 def __init__(self,*args, **kwargs): 3 print "init A&quo ...

  2. LOJ#6463 AK YOI 树分治+线段树合并

    传送门 既然是树上路径统计问题,不难想到要使用树分治,这里以点分治为例 由点分治的性质,每层只需要考虑经过重心的路径 因为需要维护路径长度在一定范围内的最大权值和,所以要用一个数据结构维护一下到根节点 ...

  3. iTem2 保持连接,解决ssh的"Write failed: Broken pipe"问题

    方法一: profiles -> sessions -> When idel, send ASCII code 问题场景 服务器环境:阿里云 Linux CentOS 主机 客户端:Mac ...

  4. C#+MapServer相关代码

    //放大的代码: private void MapZoomIn(NameValueCollection queryString) { mapObj map = Session["MapSer ...

  5. 自定义圆角ImageView控件

    这个就当工具类用吧,因为直接是继承的ImageView.所以也具备了ImageView所有的特点,不同的是,可以自动裁剪成圆角图片.看效果吧. 效果还是不错的.使用方式: 直接在配置中添加依赖 com ...

  6. Evernote Markdown Sublime使用介绍

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4002619.html 这一篇博客继续探讨:Evernote ...

  7. linux yum 安装wget、gcc、ifconfig、vim、setup

    安装wgetyum -y install wget安装gcc c语言编译器yum -y install gcc安装ifconfigyum -y install net-tools.x86_64安装vi ...

  8. PyQt4(使用ui)

    1.使用qt designer设计界面,保存为test1.ui: 2.使用pyuic4 test1.ui -o ui.py生成ui代码. 3.程序载入. import sys import ui fr ...

  9. 基于 Docker 的现代软件供应链

    [编者按]本文作者为 Marc Holmes,主要介绍一项关于现代软件供应链的调查结果.本文系国内 ITOM 管理平台 OneAPM 编译呈现,以下为正文. 3 月初,为了了解软件供应链的现状以及 D ...

  10. microsoft azure 映像发布前的检查清单

    在发布映像提交到 Azure 镜像市场之前,请确保以下检查单全部通过: 产品映像要求 产品映像必须满足如下要求: 适用于生产环境,Azure 镜像市场原则上不接受测试版本产品上架 映像为自包含映像,所 ...