fangyuan
2022-11-17 059eebfe1c54750e74e290ed7503e2cbf3f2f740
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
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;
    }
 
 
}