图片本地转webp

master
管理员 3 years ago
parent ec25ddfa79
commit 2c0207ed82

@ -0,0 +1,83 @@
package com.ruoyi.test;
import cn.hutool.core.img.Img;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.esotericsoftware.kryo.io.Input;
import org.junit.jupiter.api.Test;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class ImageTest {
@Test
public void test1(){
JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(true);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.showOpenDialog(null);
File[] fs = jfc.getSelectedFiles();
for(File f : fs) {
File outFile = new File(f.getAbsolutePath().substring(0,f.getAbsolutePath().lastIndexOf("."))+".webp");
try(
InputStream in = formatImage(Img.from(f),800,800,null);
OutputStream out = new FileOutputStream(outFile);
){
IoUtil.copy(in,out);
}catch (Exception e){
}
}
}
public InputStream formatImage(Img img, int maxWidth, int maxHeight, BufferedImage watermark) {
try {
int w = img.getImg().getWidth(null);
int h = img.getImg().getHeight(null);
if(maxWidth>0 && maxHeight > 0){
if (w > maxWidth || h > maxHeight) {
int outWidth = 0;
int outHeight = 0;
outHeight = maxWidth * h / w;
if (outHeight > maxHeight) {
outHeight = maxHeight;
outWidth = outHeight * maxWidth / h;
} else {
outWidth = maxWidth;
}
img = img.scale(outWidth, outHeight);
w = outWidth;
h = outHeight;
}
}
if (watermark != null) {
int ww = watermark.getWidth(null);
int wh = watermark.getHeight(null);
if (w > ww && h > wh) {
img = img.pressImage(watermark, 0, 0, 1f);
}
}
ByteArrayOutputStream pout = new ByteArrayOutputStream();
img.setTargetImageType("webp").write(pout);
ByteArrayInputStream pin = new ByteArrayInputStream(pout.toByteArray());
pout.close();
pout = null;
return pin;
} catch (Exception e) {
throw new RuntimeException("处理图片错误", e);
}
}
}

@ -173,6 +173,7 @@ public interface ISysUserService {
*/
int updateUserProfile(SysUser user);
/**
*
*

Loading…
Cancel
Save