最近在做一个图像识别程序,由于图片是页面上传的,需要将MultipartFile转为Mat对象
需要了解图片RGB RGBA等知识,研究了蛮久的,代码分享给大家
MultipartFile file
//转BufferedImage对象
BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
//bufferedImage转Mat
Mat src = convertMat(bufferedImage);
/**
* bufferedImage convert mat
* @param im
* @return
*/
public static Mat convertMat(BufferedImage im) {
// Convert INT to BYTE
im = toBufferedImageOfType(im, BufferedImage.TYPE_3BYTE_BGR);
// Convert bufferedimage to byte array
byte[] pixels = ((DataBufferByte) im.getRaster().getDataBuffer())
.getData();
// Create a Matrix the same size of image
Mat image = new Mat(im.getHeight(), im.getWidth(), 16);
// Fill Matrix with image values
image.put(0, 0, pixels);
return image;
}
/**
* 8-bit RGBA convert 8-bit RGB
* @param original
* @param type
* @return
*/
private static BufferedImage toBufferedImageOfType(BufferedImage original, int type) {
if (original == null) {
throw new IllegalArgumentException("original == null");
}
// Don't convert if it already has correct type
if (original.getType() == type) {
return original;
}
// Create a buffered image
BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), type);
// Draw the image onto the new buffer
Graphics2D g = image.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(original, 0, 0, null);
} finally {
g.dispose();
}
return image;
}