* @param multipartFile 文件* @param fileName 水印名字* @param fileType 1 代表图片 其它代表水印* @return 结果*/@Overridepublic String importSave(MultipartFile multipartFile, String fileName,String fileType,String fileUrl) {Assert.notNull(fileName,"水印名称不能为空");Assert.notNull(fileType,"文件类型不能为空");IAOssService service = SpringUtils.getBean(IAOssService.class);AOss oss = service.getCurrentOss();InputStream inputStream = null;try {if (oss.getCurrentType().equals("0")){CredentialsProvider credentialsProvider = new DefaultCredentialProvider(oss.getAppId(), oss.getAppKey());// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(oss.getOssUrl(), credentialsProvider);OSSObject object = ossClient.getObject(oss.getOssName(), fileUrl);if (StringUtils.isEmpty(fileUrl)){inputStream = multipartFile.getInputStream();}else {inputStream = object.getObjectContent();}}ByteArrayOutputStream baos = new ByteArrayOutputStream();/*走图片水印*/if (ConstantClass.IS_PUBLIC1.equals(fileType)){BufferedImage img = ImageIO.read(inputStream);BufferedImage newImg= new BufferedImage(img.getWidth(),img.getHeight(),BufferedImage.TYPE_INT_RGB);newImg.getGraphics().drawImage(img, 0, 0, null);int width = newImg.getWidth();int height = newImg.getHeight();int fontSize = (width+height) / 40;Graphics2D g = newImg.createGraphics();Color color = new Color(0, 255, 149);g.setColor(color);g.setFont(new Font("黑体", Font.PLAIN, fontSize));g.drawString(fileName, width - GetStrWidthUtis.getStrWidth(fileName, fontSize) - 30, height - 30);g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));g.dispose();ImageIO.write( newImg, "jpg", baos );//转换为MultipartFileRandom random = new Random();int nextInt = random.nextInt();MultipartFile multipartFiles = new MockMultipartFile(nextInt+".jpg",fileName,"image/png",baos.toByteArray());String upload = FileUploadUtils.upload(multipartFiles);inputStream.close();baos.close();return upload;}else {/*走视频水印*/try {Map ByEmail = GetStrWidthUtis.markWithContentByVideo(inputStream, fileName, "文化路径未使用");Object file1 = ByEmail.get("file");Object file2 = ByEmail.get("fileInputStream");Object file13= ByEmail.get("byte");File pdfFile = (File) file1;FileInputStream fileInputStream = new FileInputStream(pdfFile);MultipartFile multipartFileS = new MockMultipartFile(pdfFile.getName(), pdfFile.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);// InputStream inputStreamStream = new ByteArrayInputStream(ByEmail);//MultipartFile file = new MockMultipartFile(ContentType.APPLICATION_OCTET_STREAM.toString(), inputStreamStream);/*s上传阿里云OSS*/String upload = FileUploadUtils.upload(multipartFileS);inputStream.close();fileInputStream.close();return upload;}catch (Exception e){return e+"视频流异常";}}}catch (Exception e){return e+"水印接口异常";}}
工具类: GetStrWidthUtis
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.http.entity.ContentType;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameUtils;
import org.bytedeco.opencv.opencv_core.IplImage;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;public class GetStrWidthUtis {/*** 获取字符串占用的宽度* <br>* @param str 字符串* @param fontSize 文字大小* @return 字符串占用的宽度*/public static int getStrWidth(String str, int fontSize) {char[] chars = str.toCharArray();int fontSize2 = fontSize / 2;int width = 0;for (char c : chars) {int len = String.valueOf(c).getBytes().length;// 汉字为3,其余1// 可能还有一些特殊字符占用2等等,统统计为汉字if (len != 1) {width += fontSize;} else {width += fontSize2;}}return width;}public static MultipartFile file2MultipartFile(File file){MultipartFile multipartFile = null;try(FileInputStream fileInputStream = new FileInputStream(file)) {multipartFile = new MockMultipartFile(file.getName(), file.getName(),ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);} catch (Exception e) {System.out.println(e);}return multipartFile;}public static void main(String[] args) throws IOException {FileInputStream stream = new FileInputStream(new File("C:\\Users\\gf\\Videos\\IMG_2656_20240620100811A200.mp4"));Map video = markWithContentByVideo(stream, "测试水印", null);
// new FileOutputStream("C:\\Users\\gf\\Videos\\IMG_2656_20240620100811A200_1.mp4").write(video);}/*视频水印方法*//*** 视频打水印(文字)** @param fieldName 文件路径 未使用* @param waterMarkContent 水印内容* @param inputStream 文件流*/public static Map markWithContentByVideo(InputStream inputStream , String waterMarkContent, String fieldName ) {long l = System.currentTimeMillis();// 抓取视频资源org.bytedeco.javacv.Frame frame = new org.bytedeco.javacv.Frame();try {FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(inputStream);frameGrabber.start();Random random = new Random();int i = random.nextInt();File file = new File(UUID.fastUUID().toString(true) + ".mp4");try (FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(file,frameGrabber.getImageWidth(), frameGrabber.getImageHeight(), frameGrabber.getAudioChannels())) {recorder.setFormat(frameGrabber.getFormat());recorder.setSampleRate(frameGrabber.getSampleRate());recorder.setFrameRate(frameGrabber.getFrameRate());recorder.setTimestamp(frameGrabber.getTimestamp());recorder.setVideoBitrate(frameGrabber.getVideoBitrate());recorder.setVideoCodec(frameGrabber.getVideoCodec());recorder.setAudioCodec(frameGrabber.getAudioCodec());recorder.setAudioBitrate(frameGrabber.getAudioBitrate());recorder.start();Color markContentColor = new Color(180, 180, 180);while (true) {frame = frameGrabber.grabFrame();if (frame == null) {System.out.println("视频处理完成");break;}//判断图片帧if (frame.image != null) {IplImage iplImage = Java2DFrameUtils.toIplImage(frame);BufferedImage bufImg = Java2DFrameUtils.toBufferedImage(iplImage);int imgWidth = iplImage.width();int imgHeight = iplImage.height();int fontSize = (imgWidth + imgHeight) / 40;// 加水印Graphics2D graphics = bufImg.createGraphics();Color color = new Color(0, 255, 149);graphics.setColor(color);graphics.setFont(new Font("黑体", Font.PLAIN, fontSize));graphics.drawString(waterMarkContent, imgWidth - getStrWidth("imgWidth", fontSize) - 30, imgHeight - 30);graphics.dispose();
// // 创建绘图工具
// createText(markContentColor, waterMarkContent, bufImg, imgWidth, imgHeight, graphics);Frame frame1 = Java2DFrameUtils.toFrame(bufImg);recorder.record(frame1);}//设置音频if (frame.samples != null) {recorder.recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);}}recorder.stop();recorder.release();frameGrabber.stop();FileInputStream fileInputStream = new FileInputStream(file);byte[] bytes = new byte[fileInputStream.available()];fileInputStream.read(bytes);file.deleteOnExit();Map<String, Object> stringObjectHashMap = new HashMap<>();stringObjectHashMap.put("byte",bytes);stringObjectHashMap.put("fileInputStream",fileInputStream);stringObjectHashMap.put("file",file);return stringObjectHashMap;}} catch (Exception e) {e.printStackTrace();return null;}}
}