当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
Java图片处理(包括Jmagick的应用)
发布时间:2010/10/29 10:40:19 来源:城市学习网 编辑:ziteng
  近期有使用到图片的压缩处理,由于在之前用Java 处理时,在低像素的情况下,Java 处理的效果确实很差,然后尝试了用网上推荐的免费开源的第三方软件,利用Java 的jni 调用dll 文件进行处理,效果还可以。在此记录下,方便以后继续积累。
  1、纯Java 类处理图片代码
  Java代码
  /**
  * 转换图片大小,不变形
  *
  * @param img
  *            图片文件
  * @param width
  *            图片宽
  * @param height
  *            图片高
  */
  public static void changeImge(File img, int width, int height) {
  try {
  Image image = ImageIO.read(img);
  //图片尺寸的大小处理,如果长宽都小于规定大小,则返回,如果有一个大于规定大小,则等比例缩放
  int srcH = image.getHeight(null);
  int srcW = image.getWidth(null);
  if (srcH <= height && srcW <= width) {
  return;
  }
  int tmpH = width;
  int tmpW = height;
  //在长度和宽度都做了限制,不能超过设定值
  while (srcH > height || srcW > width) {
  if(srcW > width) {
  tmpH = srcH * width / srcW;
  srcH = tmpH;
  srcW=width;
  }
  if(srcH > height) {
  tmpW = srcW * height / srcH;
  srcW = tmpW;
  srcH=height;
  }
  }
  BufferedImage bufferedImage = new BufferedImage(srcW, srcH,
  BufferedImage.TYPE_3BYTE_BGR);
  bufferedImage.getGraphics().drawImage(
  image.getScaledInstance(srcW, srcH, Image.SCALE_SMOOTH), 0,
  0, srcW, srcH, null);
  FileOutputStream fos = new FileOutputStream(img);
  JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
  encoder.encode(bufferedImage);
  fos.close();
  // System.out.println("转换成功...");
  } catch (IOException e) {
  e.printStackTrace();
  throw new IllegalStateException("图片转换出错!", e);
  }
  }
  2、使用Jmagick 辅助
  Html代码
  (1)使用的windows下的jmagick-win-6.3.9-q16.zip 地址是:http://downloads.jmagick.org/6.3.9/
  (2)doc对应的api地址:http://downloads.jmagick.org/jmagick-doc/
  (3)安装imagemagick,官方网站:http://www.imagemagick.org/
  我使用的是:imagemagick-6.4.6-4-q16-windows-dll.exe :点击下载
  (4) 安装imagemagick-6.4.6-4-q16-windows-dll.exe,将 安装目录下(按自己所安装的目录找) 下的所有dll文件 copy 到系统盘下的 “c:\windows\system32\”文件夹里
  (5) 配置环境变量
  再环境变量path里添加新的值 “c:\program files\imagemagick-6.4.6-4-q16“使用ide可以不用配置
  (6)解压jmagick-win-6.3.9-q16.zip
  将 jmagick.dll 复制到系统盘下的 “c:\windows\system32\”文件夹里 和 复制到jdk的bin(例“d:\jdk6\bin”)文件里各一份
  将 jmagick.jar 复制到tomcat下的lib文件夹里 和 所使用项目的web-inf下lib文件里 各一份
  (7)web应用如果部署到tomcat下,那么最好在catalina.bat文件中改变如下设置
  set java_opts=%java_opts% -xms256m -xmx768m -xx:maxpermsize=128m – djava.util.logging.manager=org.apache.juli.classloaderlogmanager – djava.util.logging.config.file=”${catalina.base}\conf\logging.properties”
  避免heap溢出的问题,参数看你自己的机器而定。( -xms256m -xmx768m -xx:maxpermsize=128m )
  (8)还要注意如果部署到web应用,你在使用的class里面需要
  system.setproperty(“jmagick.systemclassloader”,”no”);
  要不然会报出unsatisfiedlinkerror: no jmagick in java.library.path.
  工具类:
  Java代码
  import java.awt.Dimension;
  import java.awt.Rectangle;
  import java.text.SimpleDateFormat;
  import java.util.Date;
  import magick.CompositeOperator;
  import magick.CompressionType;
  import magick.DrawInfo;
  import magick.ImageInfo;
  import magick.MagickException;
  import magick.MagickImage;
  import magick.PixelPacket;
  import magick.PreviewType;
  public class ImageUtils {
  static{
  //不能漏掉这个,不然jmagick.jar的路径找不到
  System.setProperty("jmagick.systemclassloader","no");
  } [NextPage]   /**
  * 压缩图片,不变形
  * @param filePath 源文件路径
  * @param toPath   缩略图路径
  * @param width 设定宽
  * @param height 设定长
  */
  public static void changeSize(String filePath, String toPath,int width,int height) throws MagickException{
  ImageInfo info = null;
  MagickImage image = null;
  Dimension imageDim = null;
  MagickImage scaled = null;
  try{
  info = new ImageInfo(filePath);
  image = new MagickImage(info);
  imageDim = image.getDimension();
  //图片尺寸的大小处理,如果长宽都小于规定大小,则返回,如果有一个大于规定大小,则等比例缩放
  int srcH = imageDim.width;
  int srcW = imageDim.height;
  if (srcH <= height && srcW <= width) {
  return;
  }
  int tmpH = width;
  int tmpW = height;
  //在长度和宽度都做了限制,不能超过设定值
  while (srcH > height || srcW > width) {
  if(srcW > width) {
  tmpH = srcH * width / srcW;
  srcH = tmpH;
  srcW=width;
  }
  if(srcH > height) {
  tmpW = srcW * height / srcH;
  srcW = tmpW;
  srcH=height;
  }
  }
  scaled = image.scaleImage(srcW, srcH);//小图片文件的大小.
  scaled.setFileName(toPath);
  scaled.writeImage(info);
  }finally{
  if(scaled != null){
  scaled.destroyImages();
  }
  }
  }
  /**
  * 水印(图片logo)
  * @param filePath  源文件路径
  * @param toImg     修改图路径
  * @param logoPath  logo图路径
  * @throws MagickException
  */
  public static void initLogoImg(String filePath, String toImg, String logoPath) throws MagickException {
  ImageInfo info = new ImageInfo();
  MagickImage fImage = null;
  MagickImage sImage = null;
  MagickImage fLogo = null;
  MagickImage sLogo = null;
  Dimension imageDim = null;
  Dimension logoDim = null;
  try {
  fImage = new MagickImage(new ImageInfo(filePath));
  imageDim = fImage.getDimension();
  int width = imageDim.width;
  int height = imageDim.height;
  if (width > 660) {
  height = 660 * height / width;
  width = 660;
  }
  sImage = fImage.scaleImage(width, height);
  fLogo = new MagickImage(new ImageInfo(logoPath));
  logoDim = fLogo.getDimension();
  int lw = width / 8;
  int lh = logoDim.height * lw / logoDim.width;
  sLogo = fLogo.scaleImage(lw, lh);
  sImage.compositeImage(CompositeOperator.AtopCompositeOp, sLogo,  width-(lw + lh/10), height-(lh + lh/10));
  sImage.setFileName(toImg);
  sImage.writeImage(info);
  } finally {
  if(sImage != null){
  sImage.destroyImages();
  }
  }
  }
 [NextPage]   /**
  * 水印(文字)
  * @param filePath 源文件路径
  * @param toImg    修改图路径
  * @param text     名字(文字内容自己随意)
  * @throws MagickException
  */
  public static void initTextToImg(String filePath, String toImg,  String text) throws MagickException{
  ImageInfo info = new ImageInfo(filePath);
  if (filePath.toUpperCase().endsWith("JPG") || filePath.toUpperCase().endsWith("JPEG")) {
  info.setCompression(CompressionType.JPEGCompression); //压缩类别为JPEG格式
  info.setPreviewType(PreviewType.JPEGPreview); //预览格式为JPEG格式
  info.setQuality(95);
  }
  MagickImage aImage = new MagickImage(info);
  Dimension imageDim = aImage.getDimension();
  int wideth = imageDim.width;
  int height = imageDim.height;
  if (wideth > 660) {
  height = 660 * height / wideth;
  wideth = 660;
  }
  int a = 0;
  int b = 0;
  String[] as = text.split("");
  for (String string : as) {
  if(string.matches("[\u4E00-\u9FA5]")){
  a++;
  }
  if(string.matches("[a-zA-Z0-9]")){
  b++;
  }
  }
  int tl = a*12 + b*6 + 300;
  MagickImage scaled = aImage.scaleImage(wideth, height);
  if(wideth > tl && height > 5){
  DrawInfo aInfo = new DrawInfo(info);
  aInfo.setFill(PixelPacket.queryColorDatabase("white"));
  aInfo.setUnderColor(new PixelPacket(0,0,0,100));
  aInfo.setPointsize(12);
  //解决中文乱码问题,自己可以去随意定义个自己喜欢字体,对于移植有点问题,所以暂且注释
  //     String fontPath = "C:/WINDOWS/Fonts/MSYH.TTF";
  //    aInfo.setFont(fontPath);
  aInfo.setTextAntialias(true);
  aInfo.setOpacity(0);
  aInfo.setText(" " + text + "于 " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 上传于XXXX网,版权归作者所有!");
  aInfo.setGeometry("+" + (wideth-tl) + "+" + (height-5));
  scaled.annotateImage(aInfo);
  }
  scaled.setFileName(toImg);
  scaled.writeImage(info);
  scaled.destroyImages();
  }
  /**
  * 切图
  * @param imgPath 源图路径
  * @param toPath  修改图路径
  * @param w  宽度
  * @param h 高度
  * @param x 左上角的 X 坐标
  * @param y 左上角的 Y 坐标
  * @throws MagickException
  */
  public static void cutImg(String imgPath, String toPath, int w, int h, int x, int y) throws MagickException {
  ImageInfo infoS = null;
  MagickImage image = null;
  MagickImage cropped = null;
  Rectangle rect = null;
  try {
  infoS = new ImageInfo(imgPath);
  image = new MagickImage(infoS);
  rect = new Rectangle(x, y, w, h);
  cropped = image.cropImage(rect);
  cropped.setFileName(toPath);
  cropped.writeImage(infoS);
  } finally {
  if (cropped != null) {
  cropped.destroyImages();
  }
  }
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved