在 Java 中返回 byte[] 而不是 BufferedImage?

Returning byte[] instead of BufferedImage in Java?

我正在尝试修改以下方法,使其 returns byte[](字节数组)而不是 BufferedImage。我还可以使用 returns byte[] 的另一个实现,但该实现不可配置,如下所示。那么,我怎样才能使这个方法成为 return byte[] 而不是 BufferedImage

public static BufferedImage getQRCode(String targetUrl, int width, 
    int height) {
    Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();

    hintMap.put(EncodeHintType.ERROR_CORRECTION, 
        ErrorCorrectionLevel.L);
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    BitMatrix byteMatrix = qrCodeWriter.encode(targetUrl, 
        BarcodeFormat.QR_CODE, width, height, hintMap);
    int CrunchifyWidth = byteMatrix.getWidth();

    BufferedImage image = new BufferedImage(CrunchifyWidth, 
        CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();

    Graphics2D graphics = (Graphics2D) image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
    graphics.setColor(Color.BLACK);

    for (int i = 0; i < CrunchifyWidth; i++) {
        for (int j = 0; j < CrunchifyWidth; j++) {
            if (byteMatrix.get(i, j)) {
                graphics.fillRect(i, j, 1, 1);
            }
        }
    }
    return image;
}

您需要使用类似 ByteArrayOutputStream 的东西

public static byte[] toByteArray(BufferedImage bi, String format)
        throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bi, format, baos);
        byte[] bytes = baos.toByteArray();
        return bytes;

参考:https://mkyong.com/java/how-to-convert-bufferedimage-to-byte-in-java/ }