Open deimsdeutsch opened 5 years ago
@deimsdeutsch why do you want to convert a frame in a base64? probably there is another way to work around. Remember that a Frame instance (frame
in your code) is like a container. It contains a metadata and either an image buffer or an audio sample buffer. If you want to extract the image first you must validate if it contains a not null frame.image
. Something like this:
if (frame.image != null) {
BufferedImage buf = converter.convert(frame);
if (buf != null) {
return BufToBase64(buf);
}
}
public static String BufferedImageToBase64(BufferedImage image) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "jpg", outputStream);
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outputStream.toByteArray());
}
@deimsdeutsch Your solution is almost correct, here it is fixed:
Java2DFrameConverter converter = new Java2DFrameConverter();
BufferedImage buf = converter.getBufferedImage(frame);
byte[] arr = compressImage(buf);
String base64Img = new String(Base64.getEncoder().encode(buf)));
...
public static byte[] compressImage(BufferedImage image) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos); // Using JPEG format for compression
baos.flush();
byte[] byteArray = baos.toByteArray();
baos.close();
return byteArray;
}
Optimal solution would be converting the Frame directly to base64.
Update, found a slightly more performant solution:
static {
Loader.load(opencv_java.class);
}
public static final OpenCVFrameConverter.ToMat toMatConverter = new OpenCVFrameConverter.ToMat();
public static byte[] frameToJPG(Frame frame) {
// Convert OpenCV Mat to JPEG byte array
// Create a ByteArrayOutputStream to store the JPEG data
MatOfByte outputStream = new MatOfByte();
// Convert OpenCV Mat to JavaCV Mat
Mat convertedMat = toMatConverter.convertToOrgOpenCvCoreMat(frame);
// Encode the Mat as JPEG and write it to the ByteArrayOutputStream
Imgcodecs.imencode(".jpg", convertedMat, outputStream);
// Get the byte array from the ByteArrayOutputStream
byte[] jpgData = outputStream.toArray();
// Release resources
convertedMat.release();
return jpgData;
}
Hi, how to import MatOfByte? @deimsdeutsch
EDIT: Ah ok, you are not using bytedeco in your code.
@martin-1415 You'll need to call Loader.load(opencv_java.class)
as documented here:
https://github.com/bytedeco/javacpp-presets/tree/master/opencv#documentation
Hi,
Can you please tell me how to convert org.bytedeco.javacv.Frame to base64 ? I am sorry i am asking here this but i have been searching this for weeks.
Thanks..