将上传到fastFDS上的图片(返回的路径存入数据库)
进行像素压缩处理后再次存入到数据库中
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_41761540/article/details/80137680
-
package com.msp.whg.service; -
import com.msp.whg.domain.ActivityInfo; -
import com.msp.whg.domain.InfoManage; -
import com.msp.whg.domain.ResourceManage; -
import org.eclipse.jgit.lib.FileMode; -
import org.junit.Test; -
import org.junit.runner.RunWith; -
import org.springframework.beans.factory.annotation.Autowired; -
import org.springframework.boot.test.context.SpringBootTest; -
import org.springframework.mock.web.MockMultipartFile; -
import org.springframework.test.context.junit4.SpringRunner; -
import org.springframework.web.multipart.MultipartFile; -
import javax.imageio.ImageIO; -
import javax.imageio.stream.FileImageInputStream; -
import java.awt.geom.AffineTransform; -
import java.awt.image.AffineTransformOp; -
import java.awt.image.BufferedImage; -
import java.io.*; -
import java.net.HttpURLConnection; -
import java.net.URL; -
import java.util.List; -
public void transformer( File srcImageFile, int maxPixel,InfoManage infoManage) { -
String tarImage = "C:\\Users\\Administrator\\Desktop\\2015101713_720_720.jpg"; -
//源图片文件 -
//File srcImageFile = new File(srcImage); -
//目的图片文件 -
File tarImageFile = new File(tarImage); -
// 生成图片转化对象 -
AffineTransform transform = new AffineTransform(); -
// 通过缓存读入缓存对象 -
BufferedImage image = null; -
try { -
image = ImageIO.read(srcImageFile); -
} catch (IOException e) { -
e.printStackTrace(); -
} -
int imageWidth = image.getWidth();//原图片的高度 -
int imageHeight = image.getHeight();//原图片的宽度 -
int changeWidth = 0;//压缩后图片的高度 -
int changeHeight = 0;//压缩后图片的宽度 -
double scale = 0;// 定义小图片和原图片比例 -
if (maxPixel != 0) { -
if (imageWidth > imageHeight) { -
changeWidth = maxPixel; -
scale = (double) changeWidth / (double) imageWidth; -
changeHeight = (int) (imageHeight * scale); -
} else { -
changeHeight = maxPixel; -
scale = (double) changeHeight / (double) imageHeight; -
changeWidth = (int) (imageWidth * scale); -
} -
} -
// 生成转换比例 -
transform.setToScale(scale, scale); -
// 生成转换操作对象 -
AffineTransformOp transOp = new AffineTransformOp(transform, null); -
//生成压缩图片缓冲对象 -
BufferedImage basll = new BufferedImage(changeWidth, changeHeight, BufferedImage.TYPE_3BYTE_BGR); -
//生成缩小图片 -
transOp.filter(image, basll); -
try { -
//输出缩小图片 -
ImageIO.write(basll, "jpeg",tarImageFile); -
} catch (IOException e) { -
e.printStackTrace(); -
} -
//url转换成MultipartFile -
MultipartFile file = createImg(tarImage); -
String imgUrl = null; -
try { -
//fastDFSC上传文件的方法 -
imgUrl = fastDFSClientUtil.uploadFile(file); -
} catch (IOException e) { -
e.printStackTrace(); -
} -
//修改数据库 -
infoManage.setImPath(imgUrl); -
infoManageService.update(infoManage); -
} -
@Test -
public void InfoManageUpdate(){ -
List<InfoManage> infoManageList = infoManageService.selectAll(); -
for(int i = 0 ; i < infoManageList.size() ; i++) { -
if (infoManageList.get(i).getImPath() == null || infoManageList.get(i).getImPath().length() == 0) { -
continue; -
} else { -
String srcImage = infoManageList.get(i).getImPath(); -
File file1 = null; -
//根据地址获得数据的字节流 -
byte[] btImg = getImageFromNetByUrl(srcImage); -
if (null != btImg && btImg.length > 0) { -
System.out.println("读取到:" + btImg.length + " 字节"); -
String fileName = "百度.gif"; -
//将图片写入到磁盘 -
file1 = writeImageToDisk(btImg, fileName); -
} else { -
System.out.println("没有从该连接获得内容"); -
} -
int maxPixel = 2000; //压缩后的像素 -
transformer(file1, maxPixel, infoManageList.get(i)); -
} -
} -
} -
/** -
* 将图片写入到磁盘 -
* @param img 图片数据流 -
* @param fileName 文件保存时的名称 -
*/ -
public File writeImageToDisk(byte[] img, String fileName){ -
File file = null; -
try { -
file = new File("C:\\Users\\Administrator\\Desktop\\TUPIAN\\" + fileName); -
FileOutputStream fops = new FileOutputStream(file); -
fops.write(img); -
fops.flush(); -
fops.close(); -
} catch (Exception e) { -
e.printStackTrace(); -
} -
return file; -
} -
/** -
* 根据地址获得数据的字节流 -
* @param strUrl 网络连接地址 -
* @return -
*/ -
public byte[] getImageFromNetByUrl(String strUrl){ -
try { -
URL url = new URL(strUrl); -
HttpURLConnection conn = (HttpURLConnection)url.openConnection(); -
conn.setRequestMethod("GET"); -
conn.setConnectTimeout(5 * 1000); -
InputStream inStream = conn.getInputStream();//通过输入流获取图片数据 -
byte[] btImg = readInputStream(inStream);//得到图片的二进制数据 -
return btImg; -
} catch (Exception e) { -
e.printStackTrace(); -
} -
return null; -
} -
/** -
* 根据地址获得数据的字节流 -
* @param strUrl 本地图片地址 -
* @return -
*/ -
public byte[] getImageFromNetByUrl1(String strUrl){ -
byte[] data = null; -
FileImageInputStream input = null; -
try { -
input = new FileImageInputStream(new File(strUrl)); -
ByteArrayOutputStream output = new ByteArrayOutputStream(); -
byte[] buf = new byte[1024]; -
int numBytesRead = 0; -
while ((numBytesRead = input.read(buf)) != -1) { -
output.write(buf, 0, numBytesRead); -
} -
data = output.toByteArray(); -
output.close(); -
input.close(); -
} -
catch (FileNotFoundException ex1) { -
ex1.printStackTrace(); -
} -
catch (IOException ex1) { -
ex1.printStackTrace(); -
} -
return data; -
} -
/** -
* 从输入流中获取数据 -
* @param inStream 输入流 -
* @return -
* @throws Exception -
*/ -
public static byte[] readInputStream(InputStream inStream) throws Exception{ -
ByteArrayOutputStream outStream = new ByteArrayOutputStream(); -
byte[] buffer = new byte[1024]; -
int len = 0; -
while( (len=inStream.read(buffer)) != -1 ){ -
outStream.write(buffer, 0, len); -
} -
inStream.close(); -
return outStream.toByteArray(); -
} -
/** -
* 根据url拿取file -
* -
* @param url -
* @param suffix -
* 文件后缀名 -
* */ -
public File createFileByUrl(String url, String suffix) { -
//将图片地址转换成字节流 -
byte[] byteFile = getImageFromNetByUrl1(url); -
if (byteFile != null) { -
File file = getFileFromBytes(byteFile, suffix); -
try { -
FileOutputStream fops = new FileOutputStream(file); -
fops.write(byteFile); -
fops.flush(); -
fops.close(); -
} catch (Exception e) { -
e.printStackTrace(); -
} -
return file; -
} else { -
return null; -
} -
} -
// 创建临时文件 -
private File getFileFromBytes(byte[] b, String suffix) { -
BufferedOutputStream stream = null; -
File file = null; -
try { -
file = File.createTempFile("pattern", "." + suffix); -
System.out.println("临时文件位置:"+file.getCanonicalPath()); -
/* FileOutputStream fstream = new FileOutputStream(file); -
stream = new BufferedOutputStream(fstream); -
stream.write(b);*/ -
} catch (Exception e) { -
e.printStackTrace(); -
} finally { -
if (stream != null) { -
try { -
stream.close(); -
} catch (IOException e) { -
e.printStackTrace(); -
} -
} -
} -
return file; -
} -
//url转换成MultipartFile -
public MultipartFile createImg(String url){ -
try { -
// File转换成MutipartFile -
File file = createFileByUrl(url, "jpg"); -
FileInputStream inputStream = new FileInputStream(file); -
String s = file.getName(); -
MultipartFile multipartFile = new MockMultipartFile("file",file.getName(),"null",inputStream); -
//注意这里面填啥,MultipartFile里面对应的参数就有啥,比如我只填了name,则 -
//MultipartFile.getName()只能拿到name参数,但是originalFilename是空。 -
return multipartFile; -
} catch (IOException e) { -
// TODO Auto-generated catch block -
e.printStackTrace(); -
return null; -
} -
} -
}
FastDFSClientUtil
-
package com.msp.whg.service; -
import com.github.tobato.fastdfs.domain.StorePath; -
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException; -
import com.github.tobato.fastdfs.service.FastFileStorageClient; -
import org.apache.commons.io.FilenameUtils; -
import org.apache.commons.lang.StringUtils; -
import org.slf4j.Logger; -
import org.slf4j.LoggerFactory; -
import org.springframework.beans.factory.annotation.Autowired; -
import org.springframework.stereotype.Service; -
import org.springframework.web.multipart.MultipartFile; -
import java.io.ByteArrayInputStream; -
import java.io.IOException; -
import java.nio.charset.Charset; -
@Service -
public class FastDFSClientUtil { -
private final Logger logger = LoggerFactory.getLogger(FastDFSClientUtil.class); -
@Autowired -
private FastFileStorageClient storageClient; -
/** -
* 上传文件 -
* @param file 文件对象 -
* @return 文件访问地址 -
* @throws IOException -
*/ -
public String uploadFile(MultipartFile file) throws IOException { -
logger.info(file.getName()); -
logger.info(FilenameUtils.getExtension(file.getOriginalFilename())); -
logger.info(file.getContentType()); -
logger.info(FilenameUtils.getExtension(file.getName())); -
StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null); -
return getResAccessUrl(storePath); -
} -
/** -
* 将一段字符串生成一个文件上传 -
* @param content 文件内容 -
* @param fileExtension -
* @return -
*/ -
public String uploadFile(String content, String fileExtension) { -
byte[] buff = content.getBytes(Charset.forName("UTF-8")); -
ByteArrayInputStream stream = new ByteArrayInputStream(buff); -
StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null); -
return getResAccessUrl(storePath); -
} -
// 封装图片完整URL地址 -
//http://192.168.100.166/group1/M00/00/00/wKhkplvizM6Ab1hbAAAAGkx3LfY477_big.txt -
private String getResAccessUrl(StorePath storePath) { -
String fileUrl =storePath.getFullPath(); -
return "http://192.168.100.169/"+fileUrl; -
} -
/** -
* 删除文件 -
* @param fileUrl 文件访问地址 -
* @return -
*/ -
public void deleteFile(String fileUrl) { -
if (StringUtils.isEmpty(fileUrl)) { -
return; -
} -
try { -
StorePath storePath = StorePath.praseFromUrl(fileUrl); -
storageClient.deleteFile(storePath.getGroup(), storePath.getPath()); -
} catch (FdfsUnsupportStorePathException e) { -
logger.warn(e.getMessage()); -
} -
} -
}
本文介绍了一种使用Java和FastDFS实现的图片压缩及上传方法。通过读取远程图片,将其压缩至指定像素大小,并重新上传至FastDFS服务器,同时更新数据库中图片路径。涉及关键技术包括图片读写、尺寸调整、FastDFS客户端使用等。
&spm=1001.2101.3001.5002&articleId=102722489&d=1&t=3&u=eb7c3d679f2e4a0592d55a0d603fa187)

被折叠的 条评论
为什么被折叠?



