JAVA中自动生成图像,自定义生成图像的大小

package com.pccw.business.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;

import javax.imageio.ImageIO;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

/**
 *
 * <p>
 * Title: PicReduce
 * </p>
 *
 * <p>
 * Description: 图片尺寸缩小
 * </p>
 *
 * <p>
 * Copyright: Copyright (c)
 * </p>
 *
 * <p>
 * Company:
 * </p>
 *
 * @Modified Linc
 * @version 1.0
 */
public class GeneratePicUtil {
 private String srcFile;// 源始文件名

 private String destFile;// 缩图文件名

 private int width;

 private int height;

 private Image img;

 private String destFilePath;// 如果需要保存目标文件到其他目录时需要

 // 样例:
 public static void main(String[] args) throws Exception {
   GeneratePicUtil chgImg = new GeneratePicUtil("d:\\20090629173328626493370.jpg");
   chgImg.resizeFix(500, 300);
   String path = createDirAndReturnPath("d:\\333");
   System.out.println(path);
   System.out.println(dirIsExists(path));
   File f = new File("d:\\333");
   File[] file = f.listFiles();
   for (int i = 0; i < file.length; i++) {
   System.out.println(file[i].getName());
   }
   System.out.println(deleteDirectory("D:\\预算接口表"));
   System.out.println(deleteFile("D:\\222_s.jpg"));
   System.out.println("8a84aa5c39c354030139c37fefc503e".length());
  String json = "{\"name\":\"jokewang\",\"age\":24}";
  StringBuffer sb = new StringBuffer();
  sb.append("\"");
   System.out.println(new Boolean(true).toString());
  JSONObject jsonObj = JSONObject.fromObject(json);
  String name = (String) jsonObj.get("name");
   System.out.println(name);
   System.out.println(jsonObj.getInt("age"));
  JSONArray jsonArray = new JSONArray();
  jsonArray.add("where is it ");
  jsonArray.add(9899);
  int i = jsonArray.size();
  System.out.println(jsonArray.toString());
  // System.out.println(arrayString);
  String sJson = "[{name:'张三','age':99},{name:'李四','age':'2'},{name:'王五','age':'4'}]";
  String s = "{head:'head',line:"+sJson+"}";
//  jsonArray = jsonArray.fromObject(sJson);
//  System.out.println(jsonArray.toString());
//  for (int j = 0; j < jsonArray.size(); j++) {
//   jsonObj = jsonArray.getJSONObject(j);
//   System.out.println(jsonObj.toString());
//   System.out.println(jsonObj.getString("gwcxxid"));
//   // System.out.println(jsonObj);
//  }
  jsonObj = JSONObject.fromObject(s);
  System.out.println(jsonObj.getString("head"));
  jsonArray = jsonObj.getJSONArray("line");
  for (int j = 0; j < jsonArray.size(); j++) {
   jsonObj = jsonArray.getJSONObject(j);
   System.out.println("姓名:"+jsonObj.getString("name"));
   System.out.println("年龄:"+jsonObj.getString("age"));
  }
  ClassLoader c = GeneratePicUtil.class.getClassLoader();
  System.out.println(c.getParent().getParent());
   BigDecimal b = new BigDecimal(9.655 );
         double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
         System.out.println("f1=" + f1);//f1=9.65
         BigDecimal mData = new BigDecimal("9.655").setScale(2, BigDecimal.ROUND_HALF_UP);
         System.out.println("mData=" + mData);//mData=9.66
        
         String str = "iiiiiooo000000iiiip";
         System.out.println(str.substring(str.length()-2, str.length()));
         System.out.println(8.0==8.00);
         String productNumber = "01.0004.323212320000003";
         productNumber = productNumber.replace(".", "");
         System.out.println(productNumber);
 }
 /**
  * 构造函数
  *
  * @param fileName
  *            String
  * @throws IOException
  *             构造函数参数 源文件(图片)的路径
  */
 public GeneratePicUtil(String fileName) throws IOException {
  File _file = new File(fileName); // 读入文件
  this.srcFile = _file.getName();
  this.destFile = this.srcFile
    .substring(0, this.srcFile.lastIndexOf(".")) + "_s.jpg";// 生成文件命名为原文件名
                  // +
                  // "_s"
  int length = fileName.lastIndexOf(File.separator);
  destFilePath = fileName.substring(0, length + 1);
  // System.out.println(destFilePath);
  img = javax.imageio.ImageIO.read(_file); // 构造Image对象
  width = img.getWidth(null); // 得到源图宽
  height = img.getHeight(null); // 得到源图长

 }

 /**
  * 强制压缩/放大图片到固定的大小
  *
  * @param w
  *            int 新宽度
  * @param h
  *            int 新高度
  * @throws IOException
  */
 public void resize(int w, int h) throws IOException {
  BufferedImage _image = new BufferedImage(w, h,
    BufferedImage.TYPE_INT_RGB);
  _image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
  if ((!(this.destFilePath == null)) && !"".equals(destFilePath)) {
   FileOutputStream out = new FileOutputStream(this.destFilePath
     + destFile); // 输出到文件流
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   encoder.encode(_image); // 近JPEG编码
   out.close();
  } else {
   throw new IOException("必须设置要保存的目标文件的路径");
  }
 }

 /**
  * 按照固定的比例缩放图片
  *
  * @param t
  *            double 比例
  * @throws IOException
  */
 public void resize(double t) throws IOException {
  int w = (int) (width * t);
  int h = (int) (height * t);
  resize(w, h);
 }

 /**
  * 以宽度为基准,等比例放缩图片
  *
  * @param w
  *            int 新宽度
  * @throws IOException
  */
 public void resizeByWidth(int w) throws IOException {
  int h = (int) (height * w / width);
  resize(w, h);
 }

 /**
  * 以高度为基准,等比例缩放图片
  *
  * @param h
  *            int 新高度
  * @throws IOException
  */
 public void resizeByHeight(int h) throws IOException {
  int w = (int) (width * h / height);
  resize(w, h);

 }

 /**
  * 按照最大高度限制,生成最大的等比例缩略图
  *
  * @param w
  *            int 最大宽度
  * @param h
  *            int 最大高度
  * @throws IOException
  */
 public void resizeFix(int w, int h) throws IOException {
  if (width / height > w / h) {
   resizeByWidth(w);
  } else {
   resizeByHeight(h);
  }
 }

 /**
  * 设置目标文件名 setDestFile
  *
  * @param fileName
  *            String 文件名字符串
  */
 public void setDestFile(String fileName) throws Exception {
  if (!fileName.endsWith(".jpg")) {
   throw new Exception("目标文件必须是 \".jpg\".类型");
  }
  destFile = fileName;
 }

 /**
  * 获取目标文件名 getDestFile
  */
 public String getDestFile() {
  return destFile;
 }

 /**
  * 获取图片原始宽度 getSrcWidth
  */
 public int getSrcWidth() {
  return width;
 }

 /**
  * 获取图片原始高度 getSrcHeight
  */
 public int getSrcHeight() {
  return height;
 }

 public void setDestFilePath(String destFilePath) {
  this.destFilePath = destFilePath;
 }

 /**
  * 读入图片文件
  *
  * @param fnm
  * @return BufferedImage
  */

 public static BufferedImage getImg(String fnm) {
  BufferedImage bi = null;
  try {
   bi = ImageIO.read(new File(fnm));
  } catch (Exception e) {
   e.printStackTrace();
  }
  return bi;
 }

 /**
  * 图片存盘
  *
  * @param fnm
  * @param img
  */
 public static void mkImgFile(String fnm, BufferedImage img) {
  try {
   ImageIO.write(img, "jpg", new File(fnm));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

 // 创建文件
 public static boolean CreateFile(String destFileName) {
  File file = new File(destFileName);
  if (file.exists()) {
   // System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
   return false;
  }
  if (destFileName.endsWith(File.separator)) {
   // System.out.println("创建单个文件" + destFileName + "失败,目标不能是目录!");
   return false;
  }
  if (!file.getParentFile().exists()) {
   // System.out.println("目标文件所在路径不存在,准备创建。。。");
   if (!file.getParentFile().mkdirs()) {
    // System.out.println("创建目录文件所在的目录失败!");
    return false;
   }
  }
  // 创建目标文件
  try {
   if (file.createNewFile()) {
    // System.out.println("创建单个文件" + destFileName + "成功!");
    return true;
   } else {
    // System.out.println("创建单个文件" + destFileName + "失败!");
    return false;
   }
  } catch (IOException e) {
   e.printStackTrace();
   // System.out.println("创建单个文件" + destFileName + "失败!");
   return false;
  }
 }

 public static boolean createDir(String destDirName) {
  File dir = new File(destDirName);
  // System.out.println(dir.toString());
  if (dir.exists()) {
   // System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");
   return false;
  }
  if (!destDirName.endsWith(File.separator))
   destDirName = destDirName + File.separator;
  // 创建单个目录
  if (dir.mkdirs()) {
   // System.out.println("创建目录" + destDirName + "成功!");
   return true;
  }
  return false;
 }

 // 判断文件夹是不是存在的
 /**
  *
  */
 public static boolean dirIsExists(String destDirName) {
  File dir = new File(destDirName);
  // System.out.println(dir.toString());
  if (dir.exists()) {
   System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");
   return true;
  }
  return false;
 }

 public static int fileNumber(String destDirName) {
  File f = new File(destDirName);
  File[] files = f.listFiles();
  int j = 0;
  for (int i = 0; i < files.length; i++) {
   String name = files[i].getName();
   if (name.indexOf("_") != -1) {
    continue;
   }
   j++;
  }
  return j;
 }

 /**
  * 删除单个文件
  *
  * @param sPath
  *            被删除文件的文件名
  * @return 单个文件删除成功返回true,否则返回false
  */
 public static boolean deleteFile(String sPath) {
  boolean flag = false;
  File file = new File(sPath);
  // 路径为文件且不为空则进行删除
  if (file.isFile() && file.exists()) {
   file.delete();
   flag = true;
  }
  return flag;
 }

 /**
  * 删除目录(文件夹)以及目录下的文件
  *
  * @param sPath
  *            被删除目录的文件路径
  * @return 目录删除成功返回true,否则返回false
  */
 public static boolean deleteDirectory(String sPath) {
  // 如果sPath不以文件分隔符结尾,自动添加文件分隔符
  boolean flag = false;
  if (!sPath.endsWith(File.separator)) {
   sPath = sPath + File.separator;
  }
  File dirFile = new File(sPath);
  // 如果dir对应的文件不存在,或者不是一个目录,则退出
  if (!dirFile.exists() || !dirFile.isDirectory()) {
   return false;
  }
  flag = true;
  // 删除文件夹下的所有文件(包括子目录)
  File[] files = dirFile.listFiles();
  for (int i = 0; i < files.length; i++) {
   // 删除子文件
   if (files[i].isFile()) {
    flag = deleteFile(files[i].getAbsolutePath());
    if (!flag)
     break;
   } // 删除子目录
   else {
    flag = deleteDirectory(files[i].getAbsolutePath());
    if (!flag)
     break;
   }
  }
  if (!flag)
   return false;
  // 删除当前目录
  if (dirFile.delete()) {
   return true;
  } else {
   return false;
  }
 }

 // 创建文件目录 并得到文件目录路径
 public static String createDirAndReturnPath(String destDirName) {
  File dir = new File(destDirName);
  // System.out.println(dir.toString());
  if (dir.exists()) {
   // System.out.println("创建目录" + destDirName + "失败,目标目录已存在!");
   return dir.toString();
  }
  if (!destDirName.endsWith(File.separator))
   destDirName = destDirName + File.separator;
  // 创建单个目录
  if (dir.mkdirs()) {
   // System.out.println("创建目录" + destDirName + "成功!");
   return dir.toString();
  }
  return dir.toString();
 }

 public static String createTempFile(String prefix, String suffix,
   String dirName) {
  File tempFile = null;
  try {
   if (dirName == null) {
    // 在默认文件夹下创建临时文件
    tempFile = File.createTempFile(prefix, suffix);
    return tempFile.getCanonicalPath();
   } else {
    File dir = new File(dirName);
    // 如果临时文件所在目录不存在,首先创建
    if (!dir.exists()) {
     if (!createDir(dirName)) {
      // System.out.println("创建临时文件失败,不能创建临时文件所在目录!");
      return null;
     }
    }
    tempFile = File.createTempFile(prefix, suffix, dir);
    return tempFile.getCanonicalPath();
   }
  } catch (IOException e) {
   e.printStackTrace();
   // System.out.println("创建临时文件失败" + e.getMessage());
   return null;
  }
 }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值