2 * Copyright 2009 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.google.zxing.client.j2se;
19 import com.google.zxing.common.BitMatrix;
20 import com.google.zxing.common.ByteMatrix;
22 import javax.imageio.ImageIO;
24 import java.io.OutputStream;
25 import java.io.IOException;
26 import java.awt.image.BufferedImage;
29 * Writes a {@link BitMatrix} or {@link ByteMatrix} to {@link BufferedImage}, file or stream.
30 * Provided here instead of core since it depends on Java SE libraries.
34 public final class MatrixToImageWriter {
36 private static final int BLACK = 0xFF000000;
37 private static final int WHITE = 0xFFFFFFFF;
39 private MatrixToImageWriter() {}
41 public static BufferedImage toBufferedImage(BitMatrix matrix) {
42 int width = matrix.getWidth();
43 int height = matrix.getHeight();
44 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
45 for (int x = 0; x < width; x++) {
46 for (int y = 0; y < height; y++) {
47 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
53 public static BufferedImage toBufferedImage(ByteMatrix matrix) {
54 int width = matrix.getWidth();
55 int height = matrix.getHeight();
56 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
57 for (int x = 0; x < width; x++) {
58 for (int y = 0; y < height; y++) {
59 image.setRGB(x, y, matrix.get(x, y) == 0 ? WHITE : BLACK);
65 public static void writeToFile(BitMatrix matrix, String format, File file)
67 BufferedImage image = toBufferedImage(matrix);
68 ImageIO.write(image, format, file);
71 public static void writeToFile(ByteMatrix matrix, String format, File file)
73 BufferedImage image = toBufferedImage(matrix);
74 ImageIO.write(image, format, file);
77 public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
79 BufferedImage image = toBufferedImage(matrix);
80 ImageIO.write(image, format, stream);
83 public static void writeToStream(ByteMatrix matrix, String format, OutputStream stream)
85 BufferedImage image = toBufferedImage(matrix);
86 ImageIO.write(image, format, stream);