Java圖片,視頻上傳,截取視頻幀以及文件下載和視頻IO獲取

public class FileUtil {
@Value("${img.url}")
public String imgUrl;
@Value("${video.url}")
public String videoUrl;

/**
* 保存圖片
* @param files 圖片流
* @return
*/
public String saveImg(MultipartFile[] files) {
StringBuilder builder = new StringBuilder();
for (MultipartFile file : files) {
//獲取文件名稱
String fileName = file.getOriginalFilename();
//生成新文件名稱
String newFileName = UUID.randomUUID() + fileName.substring(fileName.indexOf("."));
File startUrl = new File(imgUrl);
//建立文件夾
if (!startUrl.exists()) {
startUrl.mkdirs();
}
//生成文件
File fileSave = new File(imgUrl + newFileName);
//保存文件
try {
file.transferTo(fileSave);
builder.append("," + newFileName);
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
return builder.toString();
}

/**
* 保存視頻
* @param file 視頻流
* @return
*/
public String saveVideo(MultipartFile file) {
//獲取文件名稱
String fileName = file.getOriginalFilename();
//生成新文件名稱
String newFileName = UUID.randomUUID() + fileName.substring(fileName.indexOf("."));
File startUrl = new File(videoUrl);
//建立文件夾
if (!startUrl.exists()) {
startUrl.mkdirs();
}
//生成文件
File fileSave = new File(videoUrl + newFileName);
//保存文件
try {
file.transferTo(fileSave);
} catch (IOException e) {
e.printStackTrace();
return "error";
}
return newFileName;
}

/**
* 刪除視頻
* @param name
* @return
*/
public void deletFile(String name) {
File file = new File(videoUrl + name);
if (file.exists()) {
file.delete();
}
}

/**
* 刪除圖片
* @param name
* @return
*/
public void deletFiles(String name) {
File file = new File(imgUrl + name);
if (file.exists()) {
file.delete();
}
}

/**
* 截取視頻的幀,造成視頻的預覽圖片
*
* @param videoName 視頻名
*/
public String cutPhotoFromVedio(String videoName) {
FFmpegFrameGrabber ff = null;
String videoPath = videoUrl + videoName;
String imgPath = videoUrl + videoName.substring(0, videoName.lastIndexOf(".")) + ".jpg";
String newImgName = videoName.substring(0, videoName.lastIndexOf(".")) + ".jpg";
File targetFile = new File(imgPath);
try {
ff = new FFmpegFrameGrabber(videoPath);
ff.start();
int lenght = ff.getLengthInFrames();
int i = 0;
Frame f = null;
while (i < lenght) {
// 過濾前5幀,避免出現全黑的圖片,依本身狀況而定
f = ff.grabFrame();
if ((i > 5) && (f.image != null)) {
break;
}
i++;
}
opencv_core.IplImage img = f.image;
int owidth = img.width();
int oheight = img.height();
// 對截取的幀進行等比例縮放
int width = 800;
int height = (int) (((double) width / owidth) * oheight);
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawImage(f.image.getBufferedImage().getScaledInstance(width, height, Image.SCALE_SMOOTH),
0, 0, null);
ImageIO.write(bi, "jpg", targetFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ff != null) {
ff.stop();
}
} catch (FrameGrabber.Exception e) {
e.printStackTrace();
}
}
return newImgName;
}
}
/**
 *  文件下載
 *  fileName 文件名稱
*/
public Response download(HttpServletResponse response, String fileName) {
if (fileName != null) {
File file = new File(filePath, fileName);
if (file.exists()) {
response.reset();
response.setContentType("application/octet-stream; charset=utf-8");
try {
response.setHeader("Content-Disposition", "attachment;" +
"filename=" + new String(fileName.getBytes("UTF8"), "ISO8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] b = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(b);
while (i != -1) {
os.write(b, 0, i);
i = bis.read(b);
}
return new Response().success("文件下載成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return new Response().success();
}
/**
 *  IO讀取視頻或圖片
 *  videoName 文件名稱
*/
public void getVideo(String videoName, HttpServletResponse response) throws IOException {    response.setContentType("images/*;charset=UTF-8");    ServletOutputStream out = null;    FileInputStream ips = null;    String filePath = videoUrl + videoName;    try {        File file = new File(filePath);        if (file.exists()) {            ips = new FileInputStream(new File(filePath));            out = response.getOutputStream();            int len = 0;            byte[] buffer = new byte[1024 * 10];            while ((len = ips.read(buffer)) != -1) {                out.write(buffer, 0, len);            }        }    } catch (Exception e) {        e.printStackTrace();    } finally {        if (!StringUtils.isEmpty(out)) {            out.flush();            out.close();            ips.close();        }    }}
相關文章
相關標籤/搜索