在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java上传图片,对图片进行等比例缩放,及局部裁剪的工具类代码

2016-12-20 13:15| 发布者: zhangjf| 查看: 658| 评论: 0

摘要: import java.awt.Container;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.Image;import java.awt.MediaTracker;import java.awt.Rectangle;import java.awt.RenderingHints;import java.aw ...
  1. import java.awt.Container;
  2. import java.awt.Graphics;
  3. import java.awt.Graphics2D;
  4. import java.awt.Image;
  5. import java.awt.MediaTracker;
  6. import java.awt.Rectangle;
  7. import java.awt.RenderingHints;
  8. import java.awt.Toolkit;
  9. import java.awt.image.BufferedImage;
  10. import java.awt.image.CropImageFilter;
  11. import java.awt.image.FilteredImageSource;
  12. import java.awt.image.ImageFilter;
  13. import java.io.BufferedInputStream;
  14. import java.io.BufferedOutputStream;
  15. import java.io.File;
  16. import java.io.FileInputStream;
  17. import java.io.FileOutputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.util.UUID;
  22. import javax.imageio.ImageIO;
  23. import com.sun.image.codec.jpeg.JPEGCodec;
  24. import com.sun.image.codec.jpeg.JPEGEncodeParam;
  25. import com.sun.image.codec.jpeg.JPEGImageEncoder;
  26. public class FileUploadUtils {
  27. /**
  28. * 裁剪图片
  29. * @param input
  30. * @param basepath
  31. * @param uid
  32. * @param x
  33. * @param y
  34. * @param width
  35. * @param height
  36. * @return 绝对路径
  37. * @throws IOException
  38. */
  39. public static String cutImg(String input,String basepath,int x,int y,int width,int height) throws IOException{
  40. String path2 = basepath+"/"+ConstantUtils.USERFACETEMPPATH;
  41. String postfix = getPostfix(input);
  42. String dst = path2 +"/"+UUID.randomUUID().toString()+"."+postfix;
  43. createDir(path2);
  44. imgCut(basepath+input,dst,postfix,x,y,width,height);
  45. return dst;
  46. }
  47. /**
  48. * 裁剪图片
  49. * @param input
  50. * @param src
  51. * @param x
  52. * @param y
  53. * @param width
  54. * @param height
  55. * @throws IOException
  56. */
  57. public static void imgCut(String input,String dst,String type,int x,int y,int width,int height) throws IOException
  58. {
  59. BufferedImage fromimg = ImageIO.read(new File(input));
  60. ImageFilter cropFilter = new CropImageFilter(x,y,width,height);
  61. Image img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(fromimg.getSource(), cropFilter));
  62. BufferedImage tag = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
  63. Graphics g = tag.getGraphics();
  64. g.drawImage(img, 0, 0, null); // 绘制小图
  65. g.dispose();
  66. // 输出为文件
  67. // dir = "d:\temp\cut_image_" + i + "_" + j + ".jpg";
  68. File f = new File(dst);
  69. ImageIO.write(tag,type, f);
  70. }
  71. /**
  72. * 上传头像文件
  73. * @param src
  74. * @param basepath
  75. * @param filename
  76. * @return
  77. * @throws Exception
  78. */
  79. public static String uploadImg(File src,String basepath,String filename) throws Exception{
  80. String daypath = DateTools.getYear() + "" + DateTools.getMonth() + "" + DateTools.getMonthWeek();
  81. String temppath = ConstantUtils.BASEUPLOADPATH+"/"+ConstantUtils.ORIGINALIMGPATH+"/" + daypath;
  82. String thumbnailpath = ConstantUtils.BASEUPLOADPATH+"/"+ConstantUtils.THUMBNAILIMGPATH+"/" + daypath;
  83. String postfix = getPostfix(filename);
  84. String uuid = UUID.randomUUID().toString();
  85. String dsttempname = uuid+"."+postfix;
  86. createDir(basepath +"/"+temppath);
  87. createDir (basepath +"/"+ thumbnailpath);
  88. String dstallpath = basepath +"/"+temppath+"/"+dsttempname;
  89. String dstthumbnailpath = basepath +"/"+thumbnailpath+"/"+dsttempname;
  90. copy(src,new File(dstallpath));
  91. //对上传的文件进行 等比例 裁剪。 按照前段要展现的 height width
  92. Thumbnail(dstallpath,dstthumbnailpath,350,300,100);
  93. //返回裁剪后的路径
  94. return thumbnailpath+"/"+dsttempname;
  95. }
  96. /**
  97. * 上传文件
  98. * @param src
  99. * @param dst
  100. * @throws Exception
  101. */
  102. public static void copy(File src, File dst) throws Exception {
  103. try {
  104. InputStream in = null;
  105. OutputStream out = null;
  106. try {
  107. in = new BufferedInputStream(new FileInputStream(src), ConstantUtils.BUFFER_SIZE);
  108. out = new BufferedOutputStream(new FileOutputStream(dst), ConstantUtils.BUFFER_SIZE);
  109. byte[] buffer = new byte[ConstantUtils.BUFFER_SIZE];
  110. while (in.read(buffer) > 0) {
  111. out.write(buffer);
  112. }
  113. } finally {
  114. if (null != in) {
  115. in.close();
  116. }
  117. if (null != out) {
  118. out.close();
  119. }
  120. }
  121. } catch (Exception e) {
  122. e.printStackTrace();
  123. throw e;
  124. }
  125. }
  126. /**
  127. * 得到文件后缀 jpg
  128. * @param fileName
  129. * @return
  130. */
  131. public static String getPostfix(String fileName){
  132. if (fileName.equals(""))
  133. return "";
  134. int pos = fileName.lastIndexOf(".");
  135. if (pos < 0) {
  136. return fileName.substring(fileName.length() - 3).toLowerCase();
  137. } else {
  138. return fileName.substring(pos+1).toLowerCase();
  139. }
  140. }
  141. /**
  142. * 创建目录
  143. * @param filePath
  144. */
  145. public static void createDir(String filePath) {
  146. File myFile = new File(filePath);
  147. if (!myFile.exists()) {
  148. if (!myFile.mkdirs())
  149. System.out.println("创建目录 fail");
  150. else
  151. System.out.println("创建目录 success");
  152. }
  153. myFile = null;
  154. }
  155. /**
  156. * 等比例缩放图片
  157. * @param infile
  158. * @param outfile
  159. * @param width
  160. * @param height
  161. * @param quality
  162. * @throws IOException
  163. * @throws InterruptedException
  164. */
  165. public static void Thumbnail(String infile, String outfile, int width, int height, int quality) throws IOException, InterruptedException {
  166. // save thumbnail image to OUTFILE
  167. //System.out.println("infile:" + infile);
  168. BufferedImage thumbImage = null;
  169. BufferedOutputStream out = null;
  170. Image image = null;
  171. image = Toolkit.getDefaultToolkit().createImage(infile);
  172. MediaTracker mediaTracker = new MediaTracker(new Container());
  173. mediaTracker.addImage(image, 0);
  174. mediaTracker.waitForID(0);
  175. int thumbWidth = width;
  176. int thumbHeight = height;
  177. double thumbRatio = (double) thumbWidth / (double) thumbHeight;
  178. int imageWidth = image.getWidth(null);
  179. int imageHeight = image.getHeight(null);
  180. double imageRatio = (double) imageWidth / (double) imageHeight;
  181. if (thumbRatio < imageRatio) {
  182. thumbHeight = (int) (thumbWidth / imageRatio);
  183. } else {
  184. thumbWidth = (int) (thumbHeight * imageRatio);
  185. }
  186. thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
  187. Graphics2D graphics2D = thumbImage.createGraphics();
  188. graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  189. graphics2D.drawImage(image,0,0, thumbWidth, thumbHeight, null);
  190. out = new BufferedOutputStream(new FileOutputStream(outfile));
  191. JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  192. JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
  193. quality = Math.max(0, Math.min(quality, 100));
  194. param.setQuality((float) quality / 100.0f, false);
  195. encoder.setJPEGEncodeParam(param);
  196. encoder.encode(thumbImage);
  197. out.close();
  198. thumbImage = null;
  199. out = null;
  200. image = null;
  201. }
  202. }
复制代码

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-8 10:41

Copyright 2015-2025 djqfx

返回顶部