直接调用Imgcodecs.imwrite(filename, img)保存图片可能出错,可以先将mat转成byte[],然后再将byte生成图片。
/**
* 保存中文路径图片
* @param src
* @param filePath
*/
public static void saveByteImg(Mat src, String filePath) {
bytesToFile(matToByte(src), filePath);
}
/**
* mat转byte[]
* @param mat 图片对象
* @return
*/
public static byte[] matToByte(Mat mat) {
MatOfByte matOfByte = new MatOfByte();
Imgcodecs.imencode(".jpg", mat, matOfByte);
byte[] byteArray = matOfByte.toArray();
return byteArray;
}
/**
* byte to file
* @param buffer
* @param filePath
*/
public static void bytesToFile(byte[] buffer, final String filePath){
File file = new File(filePath);
OutputStream output = null;
BufferedOutputStream bufferedOutput = null;
try {
output = new FileOutputStream(file);
bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write(buffer);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(null!=bufferedOutput){
try {
bufferedOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(null != output){
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}