Java将OpenCV的Mat对象转换为16进制字符串

0、参考博客文章

BufferedImage与byte[]互转

Java OpenCV开发——Mat和BufferedImage互转

BufferedImage --- base64(互相转换)

1、main

    public static void main(String[] args) {
        M3();
    }

    private static void M3() {
        VideoCapture capture = new VideoCapture();
        capture.open("rtsp://account:password@192.168.0.65:554/stream0");
        int height = (int) capture.get(Videoio.CAP_PROP_FRAME_HEIGHT);
        int width = (int) capture.get(Videoio.CAP_PROP_FRAME_WIDTH);
        if (height == 0 || width == 0) {
            System.out.println("camera not found!");
            return;
        }
        Mat capImg = new Mat();
        int count = 1;
        while (count++ < 10) {
            capture.read(capImg);
            BufferedImage bufferedImage = Mat2BufImg.Mat2BufImg(capImg, ".jpg");
            String s = Mat2BufImg.bufferedImageToHex(bufferedImage, "jpg");
            System.out.println(s + "\r\n");
            int a1 = 1;
        }
        capture.release();
    }

2、Mat2BufImg

import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.List;

public class Mat2BufImg {

    /**
     * Mat转换成BufferedImage
     *
     * @param matrix        要转换的Mat
     * @param fileExtension 格式为 ".jpg", ".png", etc
     * @return
     */
    public static BufferedImage Mat2BufImg(Mat matrix, String fileExtension) {
        // convert the matrix into a matrix of bytes appropriate for
        // this file extension
        MatOfByte mob = new MatOfByte();
        Imgcodecs.imencode(fileExtension, matrix, mob);
        // convert the "matrix of bytes" into a byte array
        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");
        }

        // Don't convert if it already has correct type
        if (original.getType() != imgType) {

            // Create a buffered image
            BufferedImage image = new BufferedImage(original.getWidth(), original.getHeight(), imgType);

            // 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();
            }
        }

        byte[] pixels = ((DataBufferByte) original.getRaster().getDataBuffer()).getData();
        Mat mat = Mat.eye(original.getHeight(), original.getWidth(), matType);
        mat.put(0, 0, pixels);
        return mat;
    }

    /**
     * 将图片转换成十六进制字符串
     *
     * @param bufferedImage BufferedImage图片流
     * @param format        参数format表示图片的格式,比如jpg等
     */
    public static String bufferedImageToHex(BufferedImage bufferedImage, String format) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, format, outputStream);
            byte[] bytes = outputStream.toByteArray();
            return new BigInteger(1, bytes).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

3、另附一个demo ImgUtil

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;

public class ImgUtil {

    public static void main(String[] args) {
        String file1 = "D:/111.jpg";
        String file2 = "D:/222.jpg";

        String hexString = imageToHex(file1, "jpg");//将图片转换成十六进制字符串
        hexToImage(file2, hexString);              //将十六进制字符串转化成图片
    }

    /**
     * 将图片转换成十六进制字符串
     */
    static String imageToHex(String filePath, String format) {
        File f = new File(filePath);
        BufferedImage bi;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, format, baos);
            byte[] bytes = baos.toByteArray();
            return new BigInteger(1, bytes).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将十六进制字符串转化成图片
     */
    static void hexToImage(String filePath, String hexString) {
        byte[] bytes = stringToByte(hexString);
        try {
            FileImageOutputStream imageOutput = new FileImageOutputStream(new File(filePath));
            imageOutput.write(bytes, 0, bytes.length);
            imageOutput.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static byte[] stringToByte(String s) {
        int length = s.length() / 2;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) ((Character.digit(s.charAt(i * 2), 16) << 4) | Character.digit(s.charAt((i * 2) + 1), 16));
        }
        return bytes;
    }
}
posted @ 2021-03-11 19:59  一只桔子2233  阅读(967)  评论(0)    收藏  举报