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

来源:互联网 发布:php开源论坛 wap 编辑:程序博客网 时间:2024/05/16 15:24

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;
  }
 }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 玩游戏时出现窗口化怎么办 玩游戏时出现输入不支持怎么办 电脑玩游戏出现蓝屏怎么办 谷歌商店网页版进不去怎么办 谷歌商店为什么打不开怎么办 玩lol突然卡顿怎么办 手机上路由器管理页面打不开怎么办 苹果电脑开机页面密码打不开怎么办 逆战活动页面打不开怎么办 电脑玩lol网络卡怎么办 ios11.4qq闪退怎么办 ios11.3qq闪退怎么办 英雄联盟进入游戏界面黑屏怎么办 英雄联盟经常未响应怎么办 英雄联盟总是无响应怎么办 英雄联盟新客户端太卡怎么办 win10英雄联盟fps低怎么办 lol登游戏闪退怎么办 lol读取界面很慢怎么办 玩lol卡死黑屏怎么办 lol黑屏退不出来怎么办 电脑分辨率调高了黑屏怎么办 电脑设置分辨率黑屏了怎么办 分辨率调高了黑屏怎么办 电脑调分辨率黑屏了怎么办 科沃斯cr120遥控器丢了怎么办 买了kl色的钻戒怎么办 qq旋风没有蓝钻怎么办 手机桌面短信图标不见了怎么办 手机桌面qq音乐图标不见了怎么办 电脑显示器图标变大了怎么办 手机卡信号好但是网络不好怎么办 陌陌功能被限制怎么办 陌陌设备封了怎么办 荣耀v8手机开机键不灵怎么办 联通积分换的腾讯会员怎么办 小米6手机变卡了怎么办 微信绑定银行卡次数太多怎么办 银行卡绑定太多微信了怎么办 怎样给qq设密码怎么办 吃了心悦胶囊上火怎么办