技师头像压缩

This commit is contained in:
曹磊 2024-09-24 15:20:19 +08:00
parent 62b7640f5b
commit 86630c27b6
2 changed files with 96 additions and 37 deletions

View File

@ -83,6 +83,50 @@ public class AliFileUploadController {
}
@RequestMapping(value = "/uploadAvatar", method = RequestMethod.POST)
@ApiOperation("头像上传")
@ResponseBody
public Result uploadAvatar(@RequestParam("file") MultipartFile file){
String value = commonRepository.findOne(234).getValue();
if("1".equals(value)){
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(commonRepository.findOne(68).getValue(), commonRepository.findOne(69).getValue(), commonRepository.findOne(70).getValue());
String suffix = file.getOriginalFilename().substring(Objects.requireNonNull(file.getOriginalFilename()).lastIndexOf("."));
// 上传文件流
InputStream inputStream = null;
try {
inputStream =new ByteArrayInputStream(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
String completePath=getPath(suffix);
ossClient.putObject(commonRepository.findOne(71).getValue(), completePath, inputStream);
// 关闭OSSClient
ossClient.shutdown();
// String src = commonRepository.findOne(72).getValue()+"/"+completePath;
String src = commonRepository.findOne(19).getValue()+"/img/"+completePath;
return Result.success().put("data",src);
}else{
try
{
String http = commonRepository.findOne(19).getValue();
String[] split = http.split("://");
// 上传文件路径
String filePath ="/www/wwwroot/"+split[1]+"/file/uploadPath";
// 上传并返回新文件名称
String fileName = FileUploadUtils.uploadAvatar(filePath, file);
String url = http +fileName;
return Result.success().put("data",url);
}
catch (Exception e)
{
log.error("本地上传失败:"+e.getMessage(),e);
return Result.error(-100,"文件上传失败!");
}
}
}
@RequestMapping(value = "/uploadWatermark", method = RequestMethod.POST)
@ApiOperation("文件上传(带水印版)")
@ResponseBody

View File

@ -112,27 +112,56 @@ public class FileUploadUtils
{
throw new DescribeException("文件名太长",-100);
}
assertAllowed(file, allowedExtension);
String fileName = extractFilename(file);
File desc = getAbsoluteFile(baseDir, fileName);
file.transferTo(desc);
String pathFileName = getPathFileName(baseDir, fileName);
return pathFileName;
}
// try {
// byte[] compressedImage = compressImage(desc, 0.5f); // 压缩比例如0.5表示压缩50%
// // 将压缩后的图片保存到文件
// ImageIO.write(ImageIO.read(new ByteArrayInputStream(compressedImage)), "png", desc);
// } catch (IOException e) {
// e.printStackTrace();
// }
//
/**
* 根据文件路径上传头像
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @return 文件名称
* @throws IOException
*/
public static final String uploadAvatar(String baseDir, MultipartFile file) throws IOException
{
try
{
return uploadAvatar(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
}
catch (Exception e)
{
throw new IOException(e.getMessage(), e);
}
}
/**
* 文件头像
*
* @param baseDir 相对应用的基目录
* @param file 上传的文件
* @return 返回上传成功的文件名
*/
public static final String uploadAvatar(String baseDir, MultipartFile file, String[] allowedExtension)
throws DescribeException,IOException
{
int fileNamelength = file.getOriginalFilename().length();
if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
{
throw new DescribeException("文件名太长",-100);
}
assertAllowed(file, allowedExtension);
String fileName = extractFilename(file);
File desc = getAbsoluteFile(baseDir, fileName);
OutputStream out = Files.newOutputStream(desc.toPath());
IoUtil.copy(file.getInputStream(), out);
//file.transferTo(desc);
IoUtil.close(out);
String pathFileName = getPathFileName(baseDir, fileName);
String extension = getExtension(file);
String[] imgExtension = {"bmp", "gif", "jpg", "jpeg", "png"};
boolean isImg = false;
@ -143,25 +172,6 @@ public class FileUploadUtils
isImg = true;
}
}
// try {
// File input = new File(baseDir+"/"+fileName);
// BufferedImage image = ImageIO.read(input);
//// int width = image.getWidth();
//// int height = image.getHeight();
// double scaleFactor = 0.1; // 压缩比例为50%
// int width = (int) (image.getWidth() * scaleFactor);
// int height = (int) (image.getHeight() * scaleFactor);
//
// BufferedImage compressedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Graphics2D g2d = compressedImage.createGraphics();
// g2d.drawImage(image, 0, 0, width, height, null);
// g2d.dispose();
// ImageIO.write(compressedImage, "png", input);
//
// System.out.println("压缩成功!");
// } catch (Exception e) {
// System.out.println("压缩失败:" + e.getMessage());
// }
//如果是图片则压缩
if(isImg){
try {
@ -170,13 +180,10 @@ public class FileUploadUtils
Random random = new Random();
int randomNumber = random.nextInt(900000) + 100000; // 生成一个介于100000到999999之间的随机数
String outfilename = fileName.substring(0,fileName.lastIndexOf("/"))+"/"+sdf.format(date)+randomNumber+fileName.substring(fileName.lastIndexOf("."),fileName.length());
File inputFile = new File(baseDir + File.separator + fileName);
File outputFile = new File(baseDir + File.separator + outfilename); // 输出图片文件
String retImgName = "/file/uploadPath/"+outfilename;
float quality = 0.45f; // 压缩质量范围0.0到1.0
compressImage(inputFile, outputFile, quality);
pathFileName = retImgName;
scaledImage(inputFile, outputFile,300 ,500);
pathFileName = "/file/uploadPath/"+outfilename;
} catch (IOException e) {
e.printStackTrace();
}
@ -184,6 +191,14 @@ public class FileUploadUtils
return pathFileName;
}
public static void scaledImage(File inputFile, File outputFile, int targetWidth, int targetHeight) throws IOException {
BufferedImage bufferedImage = ImageIO.read(inputFile);
Image compressedImage = bufferedImage.getScaledInstance(targetWidth,targetHeight,Image.SCALE_SMOOTH);
BufferedImage outputImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
// 绘制缩放后的图片
outputImage.createGraphics().drawImage(compressedImage, 0, 0, null);
ImageIO.write(outputImage, "jpg", outputFile);
}
public static void compressImage(File inputFile, File outputFile, float quality) throws IOException {
// 读取图片