java将Mat对象转换为base64

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;
   }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值