/**
* 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[]转base64
* @param bytes
* @return
*/
public static String bytesToBase64(byte[] bytes) {
return "data:image/jpg;base64," + Base64.encodeBase64String(bytes);
}
public static void decodeBase64(String base64) throws IOException {
byte[] bytes = Base64.decodeBase64(base64);
OutputStream os = new FileOutputStream("F:\\opencvTest\\decode.jpg");
os.write(bytes, 0, bytes.length);
os.flush();
os.close();
}
/**
* Mat转换成BufferedImage
*
* @param matrix
* 要转换的Mat
* @param fileExtension
* 格式为 ".jpg", ".png", etc
* @return
*/
public static BufferedImage Mat2BufImg (Mat matrix, String fileExtension) {
MatOfByte mob = new MatOfByte();
Imgcodecs.imencode(fileExtension, matrix, mob);
byte[] byteArray = mob.toArray();
BufferedImage bufImage = null;
try {
InputStream in = new ByteArrayInputStream(byteArray);
bufImage = ImageIO.read(in);
} catch (Exception e) {
e.printStackTrace();
}
return bufImage;
}
/**
* BufferedImage转换成Mat
*
* @param original
* 要转换的BufferedImage
* @param imgType
* bufferedImage的类型 如 BufferedImage.TYPE_3BYTE_BGR
* @param matType
* 转换成mat的type 如 CvType.CV_8UC3
*/
public static Mat BufImg2Mat (BufferedImage original, int imgType, int matType) {
if (original == null) {
throw new IllegalArgumentException("original == null");
}
if (original.getType() != imgType) {
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), imgType);
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(original, 0, 0, null);
} finally {
g.dispose();
}
}
DataBufferByte dbi =(DataBufferByte)original.getRaster().getDataBuffer();
byte[] pixels = dbi.getData();
Mat mat = Mat.eye(original.getHeight(), original.getWidth(), matType);
mat.put(0, 0, pixels);
return mat;
}