fangyuan
2023-01-16 ecad870fe1896c8c3e48506d50bb5818974253bf
ycl-common/src/main/java/com/ycl/utils/MediaFileUtil.java
@@ -1,263 +1,263 @@
package com.ycl.utils;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.upload.FastImageFile;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.ycl.dto.media.PictureZoomParameter;
import com.ycl.dto.media.Media;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.regex.Pattern;
@Component
public class MediaFileUtil {
    private static MediaFileUtil self;
    @Value("${fdfs.groupName}")
    private String groupName;
    @PostConstruct
    private void init() {
        self = this;
    }
    @Autowired
    private FastFileStorageClient storageClient;
    private static final Pattern videoPattern = Pattern.compile("((mp4|flv|avi|rm|rmvb|wmv)(jpg|png|gif|bmp))");
    @Value("${cfg.res}")
    private String rootPath;
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM");
    public MediaFileUtil() throws IOException {
    }
    public static String uploadImage(InputStream in) throws IOException {
        return self.storageClient.uploadImage(new FastImageFile(in, in.available(), "jpg", null)).getFullPath();
    }
    public static String uploadImage(File file) throws IOException {
        FileInputStream in = new FileInputStream(file);
        return self.storageClient.uploadImage(new FastImageFile(in, in.available(), "jpg", null)).getFullPath();
    }
    /**
     * 判断文件类型
     *
     * @param fileName
     * @return
     */
    public Short getType(String fileName) {
        String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        if (".jpg".equals(ext) || ".jpeg".equals(ext) || ".png".equals(ext) || ".gif".equals(ext) || ".bmp".equals(ext)) {
            return 1;
        } else if (".mp4".equals(ext) || ".avi".equals(ext) || ".flv".equals(ext) || ".rm".equals(ext) || ".wmv".equals(ext)) {
            return 2;
        } else {
            return 0;
        }
    }
    public Media save(MultipartFile file, PictureZoomParameter zoomPar) throws Exception {
        String[] fs = file.getOriginalFilename().split("\\.");
        String ext = fs[fs.length - 1];
        switch (this.getType(file.getOriginalFilename())) {
            case 1:
                return this.savePicture(file, ext, zoomPar);
            case 2:
                return this.saveVideo(file, ext);
            default:
                return new Media();
        }
    }
    public String savePicture(InputStream inputStream, String ext) throws Exception {
        StorePath sp = storageClient.uploadFile(groupName, inputStream, inputStream.available(), ext);
        return sp.getFullPath();
    }
    public Media savePicture(MultipartFile file, String ext, PictureZoomParameter zoomPar) throws Exception {
        ByteArrayOutputStream outs = new ByteArrayOutputStream();
        Media media = new Media();
        media.setType(ext);
        String path = null;
        if (zoomPar.getWidth1() != null && zoomPar.getWidth1() > 0) {
            path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth1());
            media.setUrl1(path);
        }
        if (zoomPar.getWidth2() != null && zoomPar.getWidth2() > 0) {
            path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth2());
            media.setUrl2(path);
        }
        if (zoomPar.getWidth3() != null && zoomPar.getWidth3() > 0) {
            path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth3());
            media.setUrl3(path);
        }
        // width4为原图
        path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth4());
        media.setUrl4(path);
        return media;
    }
    /**
     * 保存视频文件
     *
     * @param file
     * @param ext
     * @return
     * @throws Exception
     */
    public Media saveVideo(MultipartFile file, String ext) throws Exception {
//        StorePath sp = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
        StorePath sp = storageClient.uploadFile(groupName, file.getInputStream(), file.getSize(), ext);
        Media media = new Media();
        media.setType(ext);
        media.setUrl1(sp.getFullPath());
        return media;
    }
    /**
     * 删除一个文件
     *
     * @param rootPath
     */
    public void removeFile(String rootPath) {
        storageClient.deleteFile(rootPath);
    }
    public void removeMedia(Media media) {
        if (!StringUtils.isEmpty(media.getUrl1())) {
            storageClient.deleteFile(media.getUrl1());
        }
        if (!StringUtils.isEmpty(media.getUrl2())) {
            storageClient.deleteFile(media.getUrl2());
        }
        if (!StringUtils.isEmpty(media.getUrl3())) {
            storageClient.deleteFile(media.getUrl3());
        }
        if (!StringUtils.isEmpty(media.getUrl4())) {
            storageClient.deleteFile(media.getUrl4());
        }
    }
    public void removeMedias(List<Media> medias) {
        if (medias != null) {
            for (Media m : medias) {
                if (!StringUtils.isEmpty(m.getUrl1())) {
                    storageClient.deleteFile(m.getUrl1());
                }
                if (!StringUtils.isEmpty(m.getUrl2())) {
                    storageClient.deleteFile(m.getUrl2());
                }
                if (!StringUtils.isEmpty(m.getUrl3())) {
                    storageClient.deleteFile(m.getUrl3());
                }
                if (!StringUtils.isEmpty(m.getUrl4())) {
                    storageClient.deleteFile(m.getUrl4());
                }
            }
        }
    }
    /**
     * 判断文件是否存在
     *
     * @param url
     * @return
     */
    public Boolean isEmpty(String url) {
        return true;
    }
    /**
     * 缩放并且上传
     *
     * @param in
     * @param ext
     * @param width
     * @return
     * @throws Exception
     */
    private String thumbAndStorage(InputStream in, String ext, Integer width) throws Exception {
        Thumbnails.Builder fileBuilder = Thumbnails.of(in).scale(1.0).outputQuality(1.0);
        BufferedImage src = fileBuilder.asBufferedImage();
        Integer w = src.getWidth(null);
        Integer destWidth = width > w ? w : width;
        ByteArrayOutputStream bouts = new ByteArrayOutputStream();
        Thumbnails.of(in).width(destWidth).toOutputStream(bouts);
        InputStream ins = this.out2In(bouts);
        StorePath sp = storageClient.uploadFile(groupName, ins, bouts.size(), ext);
//        StorePath sp = storageClient.uploadFile(ins, bouts.size(), ext, null);
        bouts.close();
        ins.close();
        return sp.getFullPath();
    }
    private String thumbAndStorageOfFile(MultipartFile file, String ext, Integer width) throws Exception {
        Thumbnails.Builder fileBuilder = Thumbnails.of(file.getInputStream()).scale(1.0).outputQuality(1.0);
        BufferedImage src = fileBuilder.asBufferedImage();
        Integer w = src.getWidth(null);
        Integer destWidth = width == null || width > w ? w : width;
        ByteArrayOutputStream bouts = new ByteArrayOutputStream();
        Thumbnails.of(file.getInputStream()).width(destWidth).toOutputStream(bouts);
        InputStream ins = this.out2In(bouts);
        StorePath sp = storageClient.uploadFile(groupName, ins, bouts.size(), ext);
//        StorePath sp = storageClient.uploadFile(ins, bouts.size(), ext, null);
        bouts.close();
        ins.close();
        return sp.getFullPath();
    }
    /**
     * 输出流转输入流
     *
     * @param outs
     * @return
     * @throws Exception
     */
    private InputStream out2In(ByteArrayOutputStream outs) throws Exception {
        InputStream ins = new ByteArrayInputStream(outs.toByteArray());
        return ins;
    }
}
//package com.ycl.utils;
//
//
//import com.github.tobato.fastdfs.domain.fdfs.StorePath;
//import com.github.tobato.fastdfs.domain.upload.FastImageFile;
//import com.github.tobato.fastdfs.service.FastFileStorageClient;
//import com.ycl.dto.media.PictureZoomParameter;
//import com.ycl.dto.media.Media;
//import net.coobird.thumbnailator.Thumbnails;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;
//import org.springframework.util.StringUtils;
//import org.springframework.web.multipart.MultipartFile;
//
//import javax.annotation.PostConstruct;
//import java.awt.image.BufferedImage;
//import java.io.*;
//import java.time.format.DateTimeFormatter;
//import java.util.List;
//import java.util.regex.Pattern;
//
//@Component
//public class MediaFileUtil {
//
//
//    private static MediaFileUtil self;
//    @Value("${fdfs.groupName}")
//    private String groupName;
//
//    @PostConstruct
//    private void init() {
//        self = this;
//    }
//
//
//    @Autowired
//    private FastFileStorageClient storageClient;
//
//
//    private static final Pattern videoPattern = Pattern.compile("((mp4|flv|avi|rm|rmvb|wmv)(jpg|png|gif|bmp))");
//
//    @Value("${cfg.res}")
//    private String rootPath;
//
//    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM");
//
//
//    public MediaFileUtil() throws IOException {
//
//    }
//
//
//    public static String uploadImage(InputStream in) throws IOException {
//
//        return self.storageClient.uploadImage(new FastImageFile(in, in.available(), "jpg", null)).getFullPath();
//    }
//
//
//    public static String uploadImage(File file) throws IOException {
//
//        FileInputStream in = new FileInputStream(file);
//        return self.storageClient.uploadImage(new FastImageFile(in, in.available(), "jpg", null)).getFullPath();
//    }
//
//
//    /**
//     * 判断文件类型
//     *
//     * @param fileName
//     * @return
//     */
//    public Short getType(String fileName) {
//
//        String ext = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
//
//        if (".jpg".equals(ext) || ".jpeg".equals(ext) || ".png".equals(ext) || ".gif".equals(ext) || ".bmp".equals(ext)) {
//            return 1;
//        } else if (".mp4".equals(ext) || ".avi".equals(ext) || ".flv".equals(ext) || ".rm".equals(ext) || ".wmv".equals(ext)) {
//            return 2;
//        } else {
//            return 0;
//        }
//    }
//
//    public Media save(MultipartFile file, PictureZoomParameter zoomPar) throws Exception {
//        String[] fs = file.getOriginalFilename().split("\\.");
//        String ext = fs[fs.length - 1];
//
//        switch (this.getType(file.getOriginalFilename())) {
//            case 1:
//                return this.savePicture(file, ext, zoomPar);
//            case 2:
//                return this.saveVideo(file, ext);
//            default:
//                return new Media();
//        }
//    }
//
//    public String savePicture(InputStream inputStream, String ext) throws Exception {
//        StorePath sp = storageClient.uploadFile(groupName, inputStream, inputStream.available(), ext);
//        return sp.getFullPath();
//    }
//
//    public Media savePicture(MultipartFile file, String ext, PictureZoomParameter zoomPar) throws Exception {
//
//        ByteArrayOutputStream outs = new ByteArrayOutputStream();
//        Media media = new Media();
//        media.setType(ext);
//        String path = null;
//        if (zoomPar.getWidth1() != null && zoomPar.getWidth1() > 0) {
//            path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth1());
//            media.setUrl1(path);
//        }
//        if (zoomPar.getWidth2() != null && zoomPar.getWidth2() > 0) {
//            path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth2());
//            media.setUrl2(path);
//        }
//        if (zoomPar.getWidth3() != null && zoomPar.getWidth3() > 0) {
//            path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth3());
//            media.setUrl3(path);
//        }
//        // width4为原图
//        path = this.thumbAndStorageOfFile(file, ext, zoomPar.getWidth4());
//        media.setUrl4(path);
//        return media;
//    }
//
//    /**
//     * 保存视频文件
//     *
//     * @param file
//     * @param ext
//     * @return
//     * @throws Exception
//     */
//    public Media saveVideo(MultipartFile file, String ext) throws Exception {
////        StorePath sp = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
//
//        StorePath sp = storageClient.uploadFile(groupName, file.getInputStream(), file.getSize(), ext);
//        Media media = new Media();
//        media.setType(ext);
//        media.setUrl1(sp.getFullPath());
//        return media;
//    }
//
//    /**
//     * 删除一个文件
//     *
//     * @param rootPath
//     */
//    public void removeFile(String rootPath) {
//        storageClient.deleteFile(rootPath);
//    }
//
//    public void removeMedia(Media media) {
//        if (!StringUtils.isEmpty(media.getUrl1())) {
//            storageClient.deleteFile(media.getUrl1());
//        }
//        if (!StringUtils.isEmpty(media.getUrl2())) {
//            storageClient.deleteFile(media.getUrl2());
//        }
//        if (!StringUtils.isEmpty(media.getUrl3())) {
//            storageClient.deleteFile(media.getUrl3());
//        }
//        if (!StringUtils.isEmpty(media.getUrl4())) {
//            storageClient.deleteFile(media.getUrl4());
//        }
//    }
//
//
//    public void removeMedias(List<Media> medias) {
//        if (medias != null) {
//            for (Media m : medias) {
//                if (!StringUtils.isEmpty(m.getUrl1())) {
//                    storageClient.deleteFile(m.getUrl1());
//                }
//                if (!StringUtils.isEmpty(m.getUrl2())) {
//                    storageClient.deleteFile(m.getUrl2());
//                }
//                if (!StringUtils.isEmpty(m.getUrl3())) {
//                    storageClient.deleteFile(m.getUrl3());
//                }
//                if (!StringUtils.isEmpty(m.getUrl4())) {
//                    storageClient.deleteFile(m.getUrl4());
//                }
//            }
//        }
//
//    }
//
//    /**
//     * 判断文件是否存在
//     *
//     * @param url
//     * @return
//     */
//    public Boolean isEmpty(String url) {
//        return true;
//    }
//
//    /**
//     * 缩放并且上传
//     *
//     * @param in
//     * @param ext
//     * @param width
//     * @return
//     * @throws Exception
//     */
//    private String thumbAndStorage(InputStream in, String ext, Integer width) throws Exception {
//
//        Thumbnails.Builder fileBuilder = Thumbnails.of(in).scale(1.0).outputQuality(1.0);
//        BufferedImage src = fileBuilder.asBufferedImage();
//
//        Integer w = src.getWidth(null);
//        Integer destWidth = width > w ? w : width;
//
//        ByteArrayOutputStream bouts = new ByteArrayOutputStream();
//        Thumbnails.of(in).width(destWidth).toOutputStream(bouts);
//        InputStream ins = this.out2In(bouts);
//
//        StorePath sp = storageClient.uploadFile(groupName, ins, bouts.size(), ext);
////        StorePath sp = storageClient.uploadFile(ins, bouts.size(), ext, null);
//        bouts.close();
//        ins.close();
//        return sp.getFullPath();
//    }
//
//    private String thumbAndStorageOfFile(MultipartFile file, String ext, Integer width) throws Exception {
//
//        Thumbnails.Builder fileBuilder = Thumbnails.of(file.getInputStream()).scale(1.0).outputQuality(1.0);
//        BufferedImage src = fileBuilder.asBufferedImage();
//
//        Integer w = src.getWidth(null);
//        Integer destWidth = width == null || width > w ? w : width;
//
//        ByteArrayOutputStream bouts = new ByteArrayOutputStream();
//        Thumbnails.of(file.getInputStream()).width(destWidth).toOutputStream(bouts);
//        InputStream ins = this.out2In(bouts);
//        StorePath sp = storageClient.uploadFile(groupName, ins, bouts.size(), ext);
////        StorePath sp = storageClient.uploadFile(ins, bouts.size(), ext, null);
//        bouts.close();
//        ins.close();
//        return sp.getFullPath();
//    }
//
//
//    /**
//     * 输出流转输入流
//     *
//     * @param outs
//     * @return
//     * @throws Exception
//     */
//    private InputStream out2In(ByteArrayOutputStream outs) throws Exception {
//        InputStream ins = new ByteArrayInputStream(outs.toByteArray());
//
//        return ins;
//    }
//
//
//}