Issue 494 round luminance values rather than truncate
[zxing.git] / javase / src / com / google / zxing / client / j2se / MatrixToImageWriter.java
1 /*
2  * Copyright 2009 ZXing authors
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.google.zxing.client.j2se;
18
19 import com.google.zxing.common.BitMatrix;
20
21 import javax.imageio.ImageIO;
22 import java.io.File;
23 import java.io.OutputStream;
24 import java.io.IOException;
25 import java.awt.image.BufferedImage;
26
27 /**
28  * Writes a {@link BitMatrix} to {@link BufferedImage},
29  * file or stream. Provided here instead of core since it depends on
30  * Java SE libraries.
31  *
32  * @author Sean Owen
33  */
34 public final class MatrixToImageWriter {
35
36   private static final int BLACK = 0xFF000000;
37   private static final int WHITE = 0xFFFFFFFF;
38
39   private MatrixToImageWriter() {}
40
41   /**
42    * Renders a {@link BitMatrix} as an image, where "false" bits are rendered
43    * as white, and "true" bits are rendered as black.
44    */
45   public static BufferedImage toBufferedImage(BitMatrix matrix) {
46     int width = matrix.getWidth();
47     int height = matrix.getHeight();
48     BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
49     for (int x = 0; x < width; x++) {
50       for (int y = 0; y < height; y++) {
51         image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
52       }
53     }
54     return image;
55   }
56
57   /**
58    * Writes a {@link BitMatrix} to a file.
59    *
60    * @see #toBufferedImage(BitMatrix)
61    */
62   public static void writeToFile(BitMatrix matrix, String format, File file)
63           throws IOException {
64     BufferedImage image = toBufferedImage(matrix);
65     ImageIO.write(image, format, file);
66   }
67
68   /**
69    * Writes a {@link BitMatrix} to a stream.
70    *
71    * @see #toBufferedImage(BitMatrix)
72    */
73   public static void writeToStream(BitMatrix matrix, String format, OutputStream stream)
74           throws IOException {
75     BufferedImage image = toBufferedImage(matrix);
76     ImageIO.write(image, format, stream);
77   }
78
79 }