Java Code Examples for java.awt.image.BufferedImage#TYPE_BYTE_BINARY

The following examples show how to use java.awt.image.BufferedImage#TYPE_BYTE_BINARY . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RleEncodingTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private static void encodeRLE4Test() throws IOException {
    // create 4bpp image
    byte[] r = new byte[16];
    r[0] = (byte)0xff;
    byte[] g = new byte[16];
    g[1] = (byte)0xff;
    byte[] b = new byte[16];
    b[2] = (byte)0xff;
    IndexColorModel icm = new IndexColorModel(4, 16, r, g, b);

    BufferedImage bimg = new BufferedImage(100, 100,
                                           BufferedImage.TYPE_BYTE_BINARY,
                                           icm);

    Graphics gr = bimg.getGraphics();
    gr.setColor(Color.green);
    gr.fillRect(0, 0, 100, 100);

    doTest(bimg, "BI_RLE4", ImageWriteParam.MODE_EXPLICIT);
}
 
Example 2
Source File: ImageUtils.java    From baidu-chain-dog with GNU General Public License v3.0 6 votes vote down vote up
private List<BufferedImage> cfsToImage(List<SubImage> subImgList){
    List<BufferedImage> bufferedImages = Lists.newArrayList();
    for (SubImage subImage : subImgList) {
        BufferedImage image = new BufferedImage(subImage.width, subImage.height, BufferedImage.TYPE_BYTE_BINARY);
        for (int x = 0; x < subImage.width; x++) {
            for (int y = 0; y < subImage.height; y++) {
                image.setRGB(x, y, Color.WHITE.getRGB());
            }
        }
        List<SubImage.Point> pixeList = subImage.getPixelList();
        for (SubImage.Point point : pixeList) {
            image.setRGB(point.x - subImage.left, point.y - subImage.top, Color.BLACK.getRGB());
        }

        // 将切割的中间图片加入到cfgList中
        bufferedImages.add(image);
    }
    return bufferedImages;
}
 
Example 3
Source File: BitDepth.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static boolean testPNGByteBinary() throws IOException {
    int width = 10;
    int height = 10;

    File f = new File("BlackStripe.png");
    BufferedImage bi = new BufferedImage(width, height,
                                         BufferedImage.TYPE_BYTE_BINARY);
    Graphics2D g = bi.createGraphics();
    g.setColor(new Color(255, 255, 255));
    g.fillRect(0, 0, width, height);

    ImageIO.write(bi, "png", f);
    BufferedImage bi2 = ImageIO.read(f);
    if (bi2.getWidth() != width || bi2.getHeight() != height) {
        System.out.println("Dimensions changed!");
        return false;
    }

    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            int rgb = bi2.getRGB(x, y);
            if (rgb != 0xffffffff) {
                System.out.println("Found a non-white pixel!");
                return false;
            }
        }
    }

    f.delete();
    return true;
}
 
Example 4
Source File: WBMPImageReader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public Iterator getImageTypes(int imageIndex)
    throws IOException {
    checkIndex(imageIndex);
    readHeader();

    BufferedImage bi =
        new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
    ArrayList list = new ArrayList(1);
    list.add(new ImageTypeSpecifier(bi));
    return list.iterator();
}
 
Example 5
Source File: WBMPImageReader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public Iterator getImageTypes(int imageIndex)
    throws IOException {
    checkIndex(imageIndex);
    readHeader();

    BufferedImage bi =
        new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
    ArrayList list = new ArrayList(1);
    list.add(new ImageTypeSpecifier(bi));
    return list.iterator();
}
 
Example 6
Source File: ImageNew.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * This determines the image type
 * 
 * @param namedStringParam
 * @return
 * @throws cfmRunTimeException
 */
private int getImageType(cfSession _session, String imageType) throws cfmRunTimeException {
	imageType = imageType.toUpperCase().trim();

	if (imageType.equals("3BYTE_BGR")) {
		return BufferedImage.TYPE_3BYTE_BGR;
	} else if (imageType.equals("4BYTE_ABGR")) {
		return BufferedImage.TYPE_4BYTE_ABGR;
	} else if (imageType.equals("4BYTE_ABGR_PRE")) {
		return BufferedImage.TYPE_4BYTE_ABGR_PRE;
	} else if (imageType.equals("BYTE_BINARY")) {
		return BufferedImage.TYPE_BYTE_BINARY;
	} else if (imageType.equals("BYTE_GRAY") || imageType.equals("GRAYSCALE")) {
		return BufferedImage.TYPE_BYTE_GRAY;
	} else if (imageType.equals("BYTE_INDEXED")) {
		return BufferedImage.TYPE_BYTE_INDEXED;
	} else if (imageType.equals("INT_ARGB") || imageType.equals("ARGB")) {
		return BufferedImage.TYPE_INT_ARGB;
	} else if (imageType.equals("INT_ARGB_PRE")) {
		return BufferedImage.TYPE_INT_ARGB_PRE;
	} else if (imageType.equals("INT_BGR")) {
		return BufferedImage.TYPE_INT_BGR;
	} else if (imageType.equals("INT_RGB") || imageType.equals("RGB")) {
		return BufferedImage.TYPE_INT_RGB;
	} else if (imageType.equals("USHORT_555_RGB")) {
		return BufferedImage.TYPE_USHORT_555_RGB;
	} else if (imageType.equals("USHORT_565_RGB")) {
		return BufferedImage.TYPE_USHORT_565_RGB;
	} else if (imageType.equals("USHORT_GRAY")) {
		return BufferedImage.TYPE_USHORT_GRAY;
	} else {
		throwException(_session, "invalid type specified: " + imageType);
	}

	return 0;
}
 
Example 7
Source File: BarcodeHelper.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
private synchronized BufferedImage getBufferedBarcodeImage(String documentNumber, BarcodeGenerator bean){
    try {
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(DPI, BufferedImage.TYPE_BYTE_BINARY,false ,0 );
        bean.generateBarcode(canvas, documentNumber);
        BufferedImage image=canvas.getBufferedImage();
        canvas.finish();
        return image;
    }
    catch(Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 8
Source File: TestCompressionBI_BITFIELDS.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    // buffered image types listed below can be saved as BI_BITFIELDS BMP
    int[] types = {BufferedImage.TYPE_3BYTE_BGR,
                   BufferedImage.TYPE_USHORT_555_RGB,
                   BufferedImage.TYPE_USHORT_565_RGB,
                   BufferedImage.TYPE_BYTE_GRAY,
                   BufferedImage.TYPE_BYTE_BINARY,
                   BufferedImage.TYPE_BYTE_INDEXED,
                   BufferedImage.TYPE_INT_BGR,
                   BufferedImage.TYPE_INT_RGB};

    for (int i = 0; i < types.length; i++) {
        System.out.println("Test image " + types[i]);
        TestCompressionBI_BITFIELDS t = new TestCompressionBI_BITFIELDS();

        BufferedImage src =
            t.createTestImage(types[i]);
        System.out.println("Image for test: " + src);
        System.out.println("SampleModel: " + src.getSampleModel());

        BufferedImage dst = null;
        try {
            dst = t.writeAndRead(src);
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }


        t.compareImages(src, dst);
    }
}
 
Example 9
Source File: BarcodeRasterizedImageProducer.java    From jasperreports with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Renderable createImage(
	JasperReportsContext jasperReportsContext,
	JRComponentElement componentElement, 
	BarcodeGenerator barcode, 
	String message
	)
{
	try
	{
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		int resolution = JRPropertiesUtil.getInstance(jasperReportsContext).getIntegerProperty(
				componentElement, PROPERTY_RESOLUTION, 300);
		boolean gray = JRPropertiesUtil.getInstance(jasperReportsContext).getBooleanProperty(
				componentElement, PROPERTY_GRAY, true);
		boolean antiAlias = JRPropertiesUtil.getInstance(jasperReportsContext).getBooleanProperty(
				componentElement, PROPERTY_ANTIALIAS, true);
		int imageType = gray ? BufferedImage.TYPE_BYTE_GRAY 
				: BufferedImage.TYPE_BYTE_BINARY;
		
		BitmapCanvasProvider provider = 
			new BitmapCanvasProvider(
				out, "image/x-png", resolution, imageType, antiAlias, 
				((Barcode4jComponent)componentElement.getComponent()).getOrientationValue().getValue()
				);
		barcode.generateBarcode(provider, message);
		provider.finish();
		
		byte[] imageData = out.toByteArray();
		return SimpleDataRenderer.getInstance(imageData);
	}
	catch (Exception e)
	{
		throw new JRRuntimeException(e);
	}
}
 
Example 10
Source File: WBMPImageReader.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public Iterator getImageTypes(int imageIndex)
    throws IOException {
    checkIndex(imageIndex);
    readHeader();

    BufferedImage bi =
        new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
    ArrayList list = new ArrayList(1);
    list.add(new ImageTypeSpecifier(bi));
    return list.iterator();
}
 
Example 11
Source File: OutputImageTests.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
Context(TestEnvironment env, Result result, int testType) {
    super(env, result);

    String content = (String)env.getModifier(contentList);
    if (content == null) {
        content = CONTENT_BLANK;
    }
    // REMIND: add option for non-opaque images
    image = createBufferedImage(size, size, content, false);

    result.setUnits(size*size);
    result.setUnitName("pixel");

    if (testType == TEST_IMAGEIO || testType == TEST_IMAGEWRITER) {
        ImageWriterSpi writerspi =
            (ImageWriterSpi)env.getModifier(imageioWriteFormatList);
        format = writerspi.getFileSuffixes()[0].toLowerCase();
        if (testType == TEST_IMAGEWRITER) {
            try {
                writer = writerspi.createWriterInstance();
            } catch (IOException e) {
                System.err.println("error creating writer");
                e.printStackTrace();
            }
            if (env.isEnabled(installListenerTog)) {
                writer.addIIOWriteProgressListener(
                    new WriteProgressListener());
            }
        }
        if (format.equals("wbmp")) {
            // REMIND: this is a hack to create an image that the
            //         WBMPImageWriter can handle (a better approach
            //         would involve checking the ImageTypeSpecifier
            //         of the writer's default image param)
            BufferedImage newimg =
                new BufferedImage(size, size,
                                  BufferedImage.TYPE_BYTE_BINARY);
            Graphics g = newimg.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            image = newimg;
        }
    } else { // testType == TEST_JPEGCODEC
        format = "jpeg";
    }

    initOutput();
}
 
Example 12
Source File: InputImageTests.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
Context(TestEnvironment env, Result result, int testType) {
    super(env, result);

    String content = (String)env.getModifier(contentList);
    if (content == null) {
        content = CONTENT_BLANK;
    }
    // REMIND: add option for non-opaque images
    image = createBufferedImage(size, size, content, false);

    result.setUnits(size*size);
    result.setUnitName("pixel");

    if (testType == TEST_IMAGEIO || testType == TEST_IMAGEREADER) {
        ImageReaderSpi readerspi =
            (ImageReaderSpi)env.getModifier(imageioReadFormatList);
        format = readerspi.getFileSuffixes()[0].toLowerCase();
        if (testType == TEST_IMAGEREADER) {
            seekForwardOnly = env.isEnabled(seekForwardOnlyTog);
            ignoreMetadata = env.isEnabled(ignoreMetadataTog);
            try {
                reader = readerspi.createReaderInstance();
            } catch (IOException e) {
                System.err.println("error creating reader");
                e.printStackTrace();
            }
            if (env.isEnabled(installListenerTog)) {
                reader.addIIOReadProgressListener(
                    new ReadProgressListener());
            }
        }
        if (format.equals("wbmp")) {
            // REMIND: this is a hack to create an image that the
            //         WBMPImageWriter can handle (a better approach
            //         would involve checking the ImageTypeSpecifier
            //         of the writer's default image param)
            BufferedImage newimg =
                new BufferedImage(size, size,
                                  BufferedImage.TYPE_BYTE_BINARY);
            Graphics g = newimg.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            image = newimg;
        }
    } else if (testType == TEST_TOOLKIT) {
        format = (String)env.getModifier(toolkitReadFormatList);
    } else { // testType == TEST_JPEGCODEC
        format = "jpeg";
    }

    initInput();
}
 
Example 13
Source File: InputImageTests.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
Context(TestEnvironment env, Result result, int testType) {
    super(env, result);

    String content = (String)env.getModifier(contentList);
    if (content == null) {
        content = CONTENT_BLANK;
    }
    // REMIND: add option for non-opaque images
    image = createBufferedImage(size, size, content, false);

    result.setUnits(size*size);
    result.setUnitName("pixel");

    if (testType == TEST_IMAGEIO || testType == TEST_IMAGEREADER) {
        ImageReaderSpi readerspi =
            (ImageReaderSpi)env.getModifier(imageioReadFormatList);
        format = readerspi.getFileSuffixes()[0].toLowerCase();
        if (testType == TEST_IMAGEREADER) {
            seekForwardOnly = env.isEnabled(seekForwardOnlyTog);
            ignoreMetadata = env.isEnabled(ignoreMetadataTog);
            try {
                reader = readerspi.createReaderInstance();
            } catch (IOException e) {
                System.err.println("error creating reader");
                e.printStackTrace();
            }
            if (env.isEnabled(installListenerTog)) {
                reader.addIIOReadProgressListener(
                    new ReadProgressListener());
            }
        }
        if (format.equals("wbmp")) {
            // REMIND: this is a hack to create an image that the
            //         WBMPImageWriter can handle (a better approach
            //         would involve checking the ImageTypeSpecifier
            //         of the writer's default image param)
            BufferedImage newimg =
                new BufferedImage(size, size,
                                  BufferedImage.TYPE_BYTE_BINARY);
            Graphics g = newimg.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            image = newimg;
        }
    } else if (testType == TEST_TOOLKIT) {
        format = (String)env.getModifier(toolkitReadFormatList);
    } else { // testType == TEST_JPEGCODEC
        format = "jpeg";
    }

    initInput();
}
 
Example 14
Source File: PixelTests.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 15
Source File: PixelTests.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 16
Source File: PixelTests.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void init() {
    pixelroot = new Group("pixel", "Pixel Access Benchmarks");

    pixeloptroot = new Group(pixelroot, "opts", "Pixel Access Options");
    doRenderTo = new Option.Toggle(pixeloptroot, "renderto",
                                   "Render to Image before test",
                                   Option.Toggle.Off);
    doRenderFrom = new Option.Toggle(pixeloptroot, "renderfrom",
                                     "Render from Image before test",
                                     Option.Toggle.Off);

    // BufferedImage Sources
    bufimgsrcroot = new Group.EnableSet(pixelroot, "src",
                                        "BufferedImage Sources");
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 1);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 2);
    new BufImg(BufferedImage.TYPE_BYTE_BINARY, 4);
    new BufImg(BufferedImage.TYPE_BYTE_INDEXED);
    new BufImg(BufferedImage.TYPE_BYTE_GRAY);
    new BufImg(BufferedImage.TYPE_USHORT_555_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_565_RGB);
    new BufImg(BufferedImage.TYPE_USHORT_GRAY);
    new BufImg(BufferedImage.TYPE_3BYTE_BGR);
    new BufImg(BufferedImage.TYPE_4BYTE_ABGR);
    new BufImg(BufferedImage.TYPE_INT_RGB);
    new BufImg(BufferedImage.TYPE_INT_BGR);
    new BufImg(BufferedImage.TYPE_INT_ARGB);

    // BufferedImage Tests
    bufimgtestroot = new Group(pixelroot, "bimgtests",
                               "BufferedImage Tests");
    new BufImgTest.GetRGB();
    new BufImgTest.SetRGB();

    // Raster Tests
    rastertestroot = new Group(pixelroot, "rastests",
                               "Raster Tests");
    new RasTest.GetDataElements();
    new RasTest.SetDataElements();
    new RasTest.GetPixel();
    new RasTest.SetPixel();

    // DataBuffer Tests
    dbtestroot = new Group(pixelroot, "dbtests",
                           "DataBuffer Tests");
    new DataBufTest.GetElem();
    new DataBufTest.SetElem();
}
 
Example 17
Source File: OutputImageTests.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
Context(TestEnvironment env, Result result, int testType) {
    super(env, result);

    String content = (String)env.getModifier(contentList);
    if (content == null) {
        content = CONTENT_BLANK;
    }
    // REMIND: add option for non-opaque images
    image = createBufferedImage(size, size, content, false);

    result.setUnits(size*size);
    result.setUnitName("pixel");

    if (testType == TEST_IMAGEIO || testType == TEST_IMAGEWRITER) {
        ImageWriterSpi writerspi =
            (ImageWriterSpi)env.getModifier(imageioWriteFormatList);
        format = writerspi.getFileSuffixes()[0].toLowerCase();
        if (testType == TEST_IMAGEWRITER) {
            try {
                writer = writerspi.createWriterInstance();
            } catch (IOException e) {
                System.err.println("error creating writer");
                e.printStackTrace();
            }
            if (env.isEnabled(installListenerTog)) {
                writer.addIIOWriteProgressListener(
                    new WriteProgressListener());
            }
        }
        if (format.equals("wbmp")) {
            // REMIND: this is a hack to create an image that the
            //         WBMPImageWriter can handle (a better approach
            //         would involve checking the ImageTypeSpecifier
            //         of the writer's default image param)
            BufferedImage newimg =
                new BufferedImage(size, size,
                                  BufferedImage.TYPE_BYTE_BINARY);
            Graphics g = newimg.createGraphics();
            g.drawImage(image, 0, 0, null);
            g.dispose();
            image = newimg;
        }
    } else { // testType == TEST_JPEGCODEC
        format = "jpeg";
    }

    initOutput();
}
 
Example 18
Source File: LosslessFactory.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Creates a new lossless encoded image XObject from a BufferedImage.
 * <p>
 * <u>New for advanced users from 2.0.12 on:</u><br>
 * If you created your image with a non standard ICC colorspace, it will be
 * preserved. (If you load images in java using ImageIO then no need to read
 * this segment) However a new colorspace will be created for each image. So
 * if you create a PDF with several such images, consider replacing the
 * colorspace with a common object to save space. This is done with
 * {@link PDImageXObject#getColorSpace()} and
 * {@link PDImageXObject#setColorSpace(org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace) PDImageXObject.setColorSpace()}
 *
 * @param document the document where the image will be created
 * @param image the BufferedImage to embed
 * @return a new image XObject
 * @throws IOException if something goes wrong
 */
public static PDImageXObject createFromImage(PDDocument document, BufferedImage image)
        throws IOException
{
    if ((image.getType() == BufferedImage.TYPE_BYTE_GRAY && image.getColorModel().getPixelSize() <= 8)
            || (image.getType() == BufferedImage.TYPE_BYTE_BINARY && image.getColorModel().getPixelSize() == 1))
    {
        return createFromGrayImage(image, document);
    }
    else
    {
        // We try to encode the image with predictor
        if (usePredictorEncoder)
        {
            PDImageXObject pdImageXObject = new PredictorEncoder(document, image).encode();
            if (pdImageXObject != null)
            {
                if (pdImageXObject.getColorSpace() == PDDeviceRGB.INSTANCE &&
                    pdImageXObject.getBitsPerComponent() < 16 &&
                    image.getWidth() * image.getHeight() <= 50 * 50)
                {
                    // also create classic compressed image, compare sizes
                    PDImageXObject pdImageXObjectClassic = createFromRGBImage(image, document);
                    if (pdImageXObjectClassic.getCOSObject().getLength() < 
                        pdImageXObject.getCOSObject().getLength())
                    {
                        pdImageXObject.getCOSObject().close();
                        return pdImageXObjectClassic;
                    }
                    else
                    {
                        pdImageXObjectClassic.getCOSObject().close();
                    }
                }
                return pdImageXObject;
            }
        }

        // Fallback: We export the image as 8-bit sRGB and might loose color information
        return createFromRGBImage(image, document);
    }
}
 
Example 19
Source File: ShortPaletteTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private static BufferedImage createImage(int numberColors) {
    return new BufferedImage(32,
                             32,
                             BufferedImage.TYPE_BYTE_BINARY,
                             createColorModel(numberColors));
}
 
Example 20
Source File: OCRUtils.java    From SuperBoot with MIT License 4 votes vote down vote up
/**
 * @param sfile   需要去噪的图像
 * @param destDir 去噪后的图像保存地址
 * @throws IOException
 */
public void cleanImage(File sfile, String destDir)
        throws IOException {
    File destF = new File(destDir);
    if (!destF.exists()) {
        destF.mkdirs();
    }

    BufferedImage bufferedImage = ImageIO.read(sfile);
    int h = bufferedImage.getHeight();
    int w = bufferedImage.getWidth();

    // 灰度化
    int[][] gray = new int[w][h];
    for (int x = 0; x < w; x++) {
        for (int y = 0; y < h; y++) {
            int argb = bufferedImage.getRGB(x, y);
            // 图像加亮(调整亮度识别率非常高)
            int r = (int) (((argb >> 16) & 0xFF) * 1.1 + 30);
            int g = (int) (((argb >> 8) & 0xFF) * 1.1 + 30);
            int b = (int) (((argb >> 0) & 0xFF) * 1.1 + 30);
            if (r >= 255) {
                r = 255;
            }
            if (g >= 255) {
                g = 255;
            }
            if (b >= 255) {
                b = 255;
            }
            gray[x][y] = (int) Math
                    .pow((Math.pow(r, 2.2) * 0.2973 + Math.pow(g, 2.2)
                            * 0.6274 + Math.pow(b, 2.2) * 0.0753), 1 / 2.2);
        }
    }

    // 二值化
    int threshold = ostu(gray, w, h);
    BufferedImage binaryBufferedImage = new BufferedImage(w, h,
            BufferedImage.TYPE_BYTE_BINARY);
    for (int x = 0; x < w; x++) {
        for (int y = 0; y < h; y++) {
            if (gray[x][y] > threshold) {
                gray[x][y] |= 0x00FFFF;
            } else {
                gray[x][y] &= 0xFF0000;
            }
            binaryBufferedImage.setRGB(x, y, gray[x][y]);
        }
    }

    // 矩阵打印
    for (int y = 0; y < h; y++) {
        for (int x = 0; x < w; x++) {
            if (isBlack(binaryBufferedImage.getRGB(x, y))) {
                System.out.print("*");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
    }

    ImageIO.write(binaryBufferedImage, "jpg", new File(destDir, sfile
            .getName()));
}