package com.yamyang.face;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
public class MatToBase64Example {
static {
// 加载OpenCV本地库
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
}
public static void main(String[] args) throws IOException {
//读取图像
Mat image = Imgcodecs.imread("F:\\2.png");
//将Mat对象转换为BufferedImage对象
BufferedImage bufferedImage = matToBufferedImage(image);
//将BufferedImage对象编码为PNG格式的字节数组
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", outputStream);
byte[] imageBytes = outputStream.toByteArray();
//将字节数组编码为Base64字符串
String base64ImageString = "data:image/png;base64," + Base64.getEncoder().encodeToString(imageBytes);
//打印Base64字符串
System.out.println(base64ImageString);
// Mat mat = Base64ToMatExample.base64ToMat(base64ImageString);
// HighGui.imshow("Image", mat);
// HighGui.waitKey();
}
private static BufferedImage matToBufferedImage(Mat matrix) {
int type = BufferedImage.TYPE_BYTE_GRAY;
if (matrix.channels() > 1) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
int bufferSize = matrix.channels() * matrix.cols() * matrix.rows();
byte[] buffer = new byte[bufferSize];
matrix.get(0, 0, buffer);
BufferedImage image = new BufferedImage(matrix.cols(), matrix.rows(), type);
final byte[] targetPixels = ((java.awt.image.DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.arraycopy(buffer, 0, targetPixels, 0, buffer.length);
return image;
}
}
java将Mat对象转换为base64
于 2023-04-21 15:31:21 首次发布