将上传到fastFDS上的图片(返回的路径存入数据库)

将上传到fastFDS上的图片(返回的路径存入数据库)

进行像素压缩处理后再次存入到数据库中

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

本文链接:https://blog.csdn.net/weixin_41761540/article/details/80137680

 
  1. package com.msp.whg.service;

  2.  
  3. import com.msp.whg.domain.ActivityInfo;

  4. import com.msp.whg.domain.InfoManage;

  5. import com.msp.whg.domain.ResourceManage;

  6. import org.eclipse.jgit.lib.FileMode;

  7. import org.junit.Test;

  8. import org.junit.runner.RunWith;

  9. import org.springframework.beans.factory.annotation.Autowired;

  10. import org.springframework.boot.test.context.SpringBootTest;

  11. import org.springframework.mock.web.MockMultipartFile;

  12. import org.springframework.test.context.junit4.SpringRunner;

  13. import org.springframework.web.multipart.MultipartFile;

  14.  
  15. import javax.imageio.ImageIO;

  16. import javax.imageio.stream.FileImageInputStream;

  17. import java.awt.geom.AffineTransform;

  18. import java.awt.image.AffineTransformOp;

  19. import java.awt.image.BufferedImage;

  20. import java.io.*;

  21. import java.net.HttpURLConnection;

  22. import java.net.URL;

  23. import java.util.List;

  24.  
  25. public void transformer( File srcImageFile, int maxPixel,InfoManage infoManage) {

  26.  
  27. String tarImage = "C:\\Users\\Administrator\\Desktop\\2015101713_720_720.jpg";

  28.  
  29. //源图片文件

  30. //File srcImageFile = new File(srcImage);

  31. //目的图片文件

  32. File tarImageFile = new File(tarImage);

  33. // 生成图片转化对象

  34. AffineTransform transform = new AffineTransform();

  35. // 通过缓存读入缓存对象

  36. BufferedImage image = null;

  37. try {

  38. image = ImageIO.read(srcImageFile);

  39. } catch (IOException e) {

  40. e.printStackTrace();

  41. }

  42. int imageWidth = image.getWidth();//原图片的高度

  43. int imageHeight = image.getHeight();//原图片的宽度

  44. int changeWidth = 0;//压缩后图片的高度

  45. int changeHeight = 0;//压缩后图片的宽度

  46. double scale = 0;// 定义小图片和原图片比例

  47. if (maxPixel != 0) {

  48. if (imageWidth > imageHeight) {

  49. changeWidth = maxPixel;

  50. scale = (double) changeWidth / (double) imageWidth;

  51. changeHeight = (int) (imageHeight * scale);

  52. } else {

  53. changeHeight = maxPixel;

  54. scale = (double) changeHeight / (double) imageHeight;

  55. changeWidth = (int) (imageWidth * scale);

  56. }

  57. }

  58. // 生成转换比例

  59. transform.setToScale(scale, scale);

  60. // 生成转换操作对象

  61. AffineTransformOp transOp = new AffineTransformOp(transform, null);

  62. //生成压缩图片缓冲对象

  63. BufferedImage basll = new BufferedImage(changeWidth, changeHeight, BufferedImage.TYPE_3BYTE_BGR);

  64. //生成缩小图片

  65. transOp.filter(image, basll);

  66. try {

  67. //输出缩小图片

  68. ImageIO.write(basll, "jpeg",tarImageFile);

  69. } catch (IOException e) {

  70. e.printStackTrace();

  71. }

  72.  
  73. //url转换成MultipartFile

  74. MultipartFile file = createImg(tarImage);

  75.  
  76. String imgUrl = null;

  77. try {

  78. //fastDFSC上传文件的方法

  79. imgUrl = fastDFSClientUtil.uploadFile(file);

  80. } catch (IOException e) {

  81. e.printStackTrace();

  82. }

  83. //修改数据库

  84. infoManage.setImPath(imgUrl);

  85. infoManageService.update(infoManage);

  86. }

  87.  
  88. @Test

  89. public void InfoManageUpdate(){

  90. List<InfoManage> infoManageList = infoManageService.selectAll();

  91. for(int i = 0 ; i < infoManageList.size() ; i++) {

  92. if (infoManageList.get(i).getImPath() == null || infoManageList.get(i).getImPath().length() == 0) {

  93. continue;

  94. } else {

  95.  
  96. String srcImage = infoManageList.get(i).getImPath();

  97. File file1 = null;

  98. //根据地址获得数据的字节流

  99. byte[] btImg = getImageFromNetByUrl(srcImage);

  100.  
  101. if (null != btImg && btImg.length > 0) {

  102. System.out.println("读取到:" + btImg.length + " 字节");

  103. String fileName = "百度.gif";

  104.  
  105. //将图片写入到磁盘

  106. file1 = writeImageToDisk(btImg, fileName);

  107. } else {

  108. System.out.println("没有从该连接获得内容");

  109. }

  110. int maxPixel = 2000; //压缩后的像素

  111. transformer(file1, maxPixel, infoManageList.get(i));

  112. }

  113. }

  114. }

  115.  
  116. /**

  117. * 将图片写入到磁盘

  118. * @param img 图片数据流

  119. * @param fileName 文件保存时的名称

  120. */

  121. public File writeImageToDisk(byte[] img, String fileName){

  122. File file = null;

  123. try {

  124. file = new File("C:\\Users\\Administrator\\Desktop\\TUPIAN\\" + fileName);

  125. FileOutputStream fops = new FileOutputStream(file);

  126. fops.write(img);

  127. fops.flush();

  128. fops.close();

  129. } catch (Exception e) {

  130. e.printStackTrace();

  131. }

  132. return file;

  133. }

  134.  
  135. /**

  136. * 根据地址获得数据的字节流

  137. * @param strUrl 网络连接地址

  138. * @return

  139. */

  140. public byte[] getImageFromNetByUrl(String strUrl){

  141. try {

  142. URL url = new URL(strUrl);

  143. HttpURLConnection conn = (HttpURLConnection)url.openConnection();

  144. conn.setRequestMethod("GET");

  145. conn.setConnectTimeout(5 * 1000);

  146. InputStream inStream = conn.getInputStream();//通过输入流获取图片数据

  147. byte[] btImg = readInputStream(inStream);//得到图片的二进制数据

  148. return btImg;

  149. } catch (Exception e) {

  150. e.printStackTrace();

  151. }

  152. return null;

  153. }

  154.  
  155. /**

  156. * 根据地址获得数据的字节流

  157. * @param strUrl 本地图片地址

  158. * @return

  159. */

  160. public byte[] getImageFromNetByUrl1(String strUrl){

  161. byte[] data = null;

  162. FileImageInputStream input = null;

  163. try {

  164. input = new FileImageInputStream(new File(strUrl));

  165. ByteArrayOutputStream output = new ByteArrayOutputStream();

  166. byte[] buf = new byte[1024];

  167. int numBytesRead = 0;

  168. while ((numBytesRead = input.read(buf)) != -1) {

  169. output.write(buf, 0, numBytesRead);

  170. }

  171. data = output.toByteArray();

  172. output.close();

  173. input.close();

  174. }

  175. catch (FileNotFoundException ex1) {

  176. ex1.printStackTrace();

  177. }

  178. catch (IOException ex1) {

  179. ex1.printStackTrace();

  180. }

  181. return data;

  182. }

  183.  
  184. /**

  185. * 从输入流中获取数据

  186. * @param inStream 输入流

  187. * @return

  188. * @throws Exception

  189. */

  190. public static byte[] readInputStream(InputStream inStream) throws Exception{

  191. ByteArrayOutputStream outStream = new ByteArrayOutputStream();

  192. byte[] buffer = new byte[1024];

  193. int len = 0;

  194. while( (len=inStream.read(buffer)) != -1 ){

  195. outStream.write(buffer, 0, len);

  196. }

  197. inStream.close();

  198. return outStream.toByteArray();

  199. }

  200.  
  201. /**

  202. * 根据url拿取file

  203. *

  204. * @param url

  205. * @param suffix

  206. * 文件后缀名

  207. * */

  208. public File createFileByUrl(String url, String suffix) {

  209. //将图片地址转换成字节流

  210. byte[] byteFile = getImageFromNetByUrl1(url);

  211. if (byteFile != null) {

  212. File file = getFileFromBytes(byteFile, suffix);

  213. try {

  214. FileOutputStream fops = new FileOutputStream(file);

  215. fops.write(byteFile);

  216. fops.flush();

  217. fops.close();

  218. } catch (Exception e) {

  219. e.printStackTrace();

  220. }

  221. return file;

  222. } else {

  223. return null;

  224. }

  225. }

  226.  
  227. // 创建临时文件

  228. private File getFileFromBytes(byte[] b, String suffix) {

  229. BufferedOutputStream stream = null;

  230. File file = null;

  231. try {

  232. file = File.createTempFile("pattern", "." + suffix);

  233. System.out.println("临时文件位置:"+file.getCanonicalPath());

  234. /* FileOutputStream fstream = new FileOutputStream(file);

  235. stream = new BufferedOutputStream(fstream);

  236. stream.write(b);*/

  237. } catch (Exception e) {

  238. e.printStackTrace();

  239. } finally {

  240. if (stream != null) {

  241. try {

  242. stream.close();

  243. } catch (IOException e) {

  244. e.printStackTrace();

  245. }

  246. }

  247. }

  248. return file;

  249. }

  250.  
  251.  
  252.  
  253. //url转换成MultipartFile

  254. public MultipartFile createImg(String url){

  255. try {

  256. // File转换成MutipartFile

  257. File file = createFileByUrl(url, "jpg");

  258. FileInputStream inputStream = new FileInputStream(file);

  259. String s = file.getName();

  260. MultipartFile multipartFile = new MockMultipartFile("file",file.getName(),"null",inputStream);

  261. //注意这里面填啥,MultipartFile里面对应的参数就有啥,比如我只填了name,则

  262. //MultipartFile.getName()只能拿到name参数,但是originalFilename是空。

  263. return multipartFile;

  264. } catch (IOException e) {

  265. // TODO Auto-generated catch block

  266. e.printStackTrace();

  267. return null;

  268. }

  269. }

  270.  
  271.  
  272. }

 

FastDFSClientUtil

 

 
  1. package com.msp.whg.service;

  2.  
  3. import com.github.tobato.fastdfs.domain.StorePath;

  4. import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;

  5. import com.github.tobato.fastdfs.service.FastFileStorageClient;

  6. import org.apache.commons.io.FilenameUtils;

  7. import org.apache.commons.lang.StringUtils;

  8. import org.slf4j.Logger;

  9. import org.slf4j.LoggerFactory;

  10. import org.springframework.beans.factory.annotation.Autowired;

  11. import org.springframework.stereotype.Service;

  12. import org.springframework.web.multipart.MultipartFile;

  13.  
  14. import java.io.ByteArrayInputStream;

  15. import java.io.IOException;

  16. import java.nio.charset.Charset;

  17.  
  18.  
  19. @Service

  20. public class FastDFSClientUtil {

  21. private final Logger logger = LoggerFactory.getLogger(FastDFSClientUtil.class);

  22.  
  23. @Autowired

  24. private FastFileStorageClient storageClient;

  25.  
  26. /**

  27. * 上传文件

  28. * @param file 文件对象

  29. * @return 文件访问地址

  30. * @throws IOException

  31. */

  32. public String uploadFile(MultipartFile file) throws IOException {

  33. logger.info(file.getName());

  34. logger.info(FilenameUtils.getExtension(file.getOriginalFilename()));

  35. logger.info(file.getContentType());

  36. logger.info(FilenameUtils.getExtension(file.getName()));

  37. StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);

  38. return getResAccessUrl(storePath);

  39. }

  40.  
  41. /**

  42. * 将一段字符串生成一个文件上传

  43. * @param content 文件内容

  44. * @param fileExtension

  45. * @return

  46. */

  47. public String uploadFile(String content, String fileExtension) {

  48. byte[] buff = content.getBytes(Charset.forName("UTF-8"));

  49. ByteArrayInputStream stream = new ByteArrayInputStream(buff);

  50. StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);

  51. return getResAccessUrl(storePath);

  52. }

  53.  
  54. // 封装图片完整URL地址

  55. //http://192.168.100.166/group1/M00/00/00/wKhkplvizM6Ab1hbAAAAGkx3LfY477_big.txt

  56. private String getResAccessUrl(StorePath storePath) {

  57. String fileUrl =storePath.getFullPath();

  58. return "http://192.168.100.169/"+fileUrl;

  59. }

  60.  
  61. /**

  62. * 删除文件

  63. * @param fileUrl 文件访问地址

  64. * @return

  65. */

  66. public void deleteFile(String fileUrl) {

  67. if (StringUtils.isEmpty(fileUrl)) {

  68. return;

  69. }

  70. try {

  71. StorePath storePath = StorePath.praseFromUrl(fileUrl);

  72. storageClient.deleteFile(storePath.getGroup(), storePath.getPath());

  73. } catch (FdfsUnsupportStorePathException e) {

  74. logger.warn(e.getMessage());

  75. }

  76. }

  77. }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值