Java Code Examples for javax.imageio.ImageIO#read()

The following examples show how to use javax.imageio.ImageIO#read() . These examples are extracted from open source projects. 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
/** Creates a new instance of TrackView */
public TrackView() {
    try {
        car = ImageIO.read(TrackView.class.getResource("images/beetle_red.gif"));
        track = ImageIO.read(TrackView.class.getResource("images/track.jpg"));
    } catch (Exception e) {
        System.out.println("Problem loading track/car images: " + e);
    }
    carPosition = new Point(START_POS.x, START_POS.y);
    carW = car.getWidth();
    carH = car.getHeight();
    carWHalf = carW / 2;
    carHHalf = carH / 2;
    trackW = track.getWidth();
    trackH = track.getHeight();
}
 
Example 2
Source Project: GraphicCR   File: GraphicC2Translator.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 去噪
 * 
 * @param picFile 图形验证码文件
 * @return
 * @throws Exception
 */
private BufferedImage denoise(File picFile) throws Exception {
    BufferedImage img = ImageIO.read(picFile);
    int width = img.getWidth();
    int height = img.getHeight();
    final int TARGET = 0xff000099;
    for (int x = 0; x < width; ++x) {
        for (int y = 0; y < height; ++y) {
            if (img.getRGB(x, y) == TARGET) {
                img.setRGB(x, y, TARGET_COLOR);
            } else {
                img.setRGB(x, y, USELESS_COLOR);
            }
        }
    }
    return img;
}
 
Example 3
Source Project: java-study   File: QrCodeCreateUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 读二维码并输出携带的信息
 */
public static void readQrCode(InputStream inputStream) throws IOException {
    //从输入流中获取字符串信息
    BufferedImage image = ImageIO.read(inputStream);
    //将图像转换为二进制位图源
    LuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    QRCodeReader reader = new QRCodeReader();
    Result result = null;
    try {
        result = reader.decode(bitmap);
    } catch (ReaderException e) {
        e.printStackTrace();
    }
    System.out.println(result.getText());
}
 
Example 4
Source Project: jaamsim   File: ImageInput.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void parse(Entity thisEnt, KeywordIndex kw) throws InputErrorException {
	BufferedImage temp;
	URI uri = Input.parseURI(kw);

	// Confirm that the file exists
	if (!InputAgent.fileExists(uri))
		throw new InputErrorException("The specified file does not exist.\n" +
				"File path = %s", kw.getArg(0));

	try {
		temp = ImageIO.read(uri.toURL());
	}
	catch (Exception ex) {
		throw new InputErrorException("Bad image file");
	}

	value = temp;
}
 
Example 5
/**
 * 1pxだけ違う画像を比較する.透明度が0x00の場合 => 成功
 */
@Test
public void testCompare_different_but_clear_1px() throws Exception {
	BufferedImage image1 = ImageIO.read(getClass().getResource("hifive_logo.png"));
	BufferedImage image2 = ImageIO.read(getClass().getResource("hifive_logo.png"));

	// 1pxだけ色を変える
	Random random = new Random();
	int x = random.nextInt(image2.getWidth());
	int y = random.nextInt(image2.getHeight());
	image2.setRGB(x, y, (image2.getRGB(x, y) - 1) & 0x00FFFFFF);

	Rectangle rectangle = new Rectangle(0, 0, image1.getWidth(), image2.getHeight());

	ImageComparedResult result = new IgnoringClearPixelsImageComparator().compare(image1, rectangle, image2,
			rectangle);

	assertThat(result.isSucceeded(), is(true));
	assertThat(result.isFailed(), is(false));
}
 
Example 6
private void createImages() {
    try {
        final File templateImageFile = ConstellationInstalledFileLocator.locate(
                "modules/ext/data/" + TEMPLATE_IMAGE_PATH,
                "au.gov.asd.tac.constellation.views.mapview",
                false, ConstellationPointMarker.class.getProtectionDomain());
        final BufferedImage templateImage = ImageIO.read(templateImageFile);
        TEMPLATE_IMAGE = new PImage(templateImage.getWidth(), templateImage.getHeight(), PConstants.ARGB);
        TEMPLATE_IMAGE.loadPixels();
        templateImage.getRGB(0, 0, TEMPLATE_IMAGE.width, TEMPLATE_IMAGE.height, TEMPLATE_IMAGE.pixels, 0, TEMPLATE_IMAGE.width);
        TEMPLATE_IMAGE.updatePixels();

        POINT_X_OFFSET = TEMPLATE_IMAGE.width / 2;
        POINT_Y_OFFSET = TEMPLATE_IMAGE.height;
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}
 
Example 7
Source Project: r2cloud   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static void rotateImage(File result) {
	try {
		BufferedImage image;
		try (FileInputStream fis = new FileInputStream(result)) {
			image = ImageIO.read(fis);
		}
		AffineTransform tx = AffineTransform.getScaleInstance(-1, -1);
		tx.translate(-image.getWidth(null), -image.getHeight(null));
		AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
		image = op.filter(image, null);
		try (FileOutputStream fos = new FileOutputStream(result)) {
			ImageIO.write(image, "jpg", fos);
		}
	} catch (Exception e) {
		LOG.error("unable to rotate image", e);
	}
}
 
Example 8
private BufferedImage renderDocumentWithWkhtml(String url) throws Exception, IOException, InterruptedException {
		if (!new File(configService.getValue(ConfigValue.WkhtmlToImageToolPath)).exists()) {
			throw new Exception("Preview generation via wkhtmltoimage failed: " + configService.getValue(ConfigValue.WkhtmlToImageToolPath) + " does not exist");
		}
		
		File imageTempFile = File.createTempFile("preview_", ".png", AgnUtils.createDirectory(PREVIEW_FILE_DIRECTORY));
		
		String[] command = new String[] {
			configService.getValue(ConfigValue.WkhtmlToImageToolPath),
//			"--crop-x", Integer.toString(0),
//			"--crop-y", Integer.toString(0),
//			"--crop-w", Integer.toString(maxWidth),
//			"--crop-h", Integer.toString(maxHeight),
//			"--format, png",
            "--quality", Integer.toString(50),
			url,
			imageTempFile.getAbsolutePath()};
		
		Process process = Runtime.getRuntime().exec(command);
		process.waitFor();
		
		if (!imageTempFile.exists() || imageTempFile.length() == 0) {
			throw new Exception("Preview generation via wkhtmltoimage failed: \n" + StringUtils.join(command, "\n"));
		}
		
		BufferedImage image = ImageIO.read(imageTempFile);
		
		imageTempFile.delete();
		
		return image;
	}
 
Example 9
public void doTest() {
    File pwd = new File(".");
    try {
        File f = File.createTempFile("transparency_test_", ".gif", pwd);
        System.out.println("file: " + f.getCanonicalPath());

        ImageWriter w = ImageIO.getImageWritersByFormatName("GIF").next();

        ImageWriterSpi spi = w.getOriginatingProvider();

        boolean succeed_write = ImageIO.write(src, "gif", f);

        if (!succeed_write) {
            throw new RuntimeException("Test failed: failed to write src.");
        }

        dst = ImageIO.read(f);

        checkResult(src, dst);

    } catch (IOException e) {
        throw new RuntimeException("Test failed.", e);
    }
}
 
Example 10
Source Project: jump-jump-game   File: AdbToolKit.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isImageOk() throws IOException {
    BufferedImage image = ImageIO.read(new File(SettingToolkit.getScreencapFilePathName()));
    if (image == null) {
        return false;
    }else{
        return true;
    }
}
 
Example 11
Source Project: cuba   File: DesktopEmbedded.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setSource(@Nullable URL src) {
    if (src != null) {
        try {
            BufferedImage image = ImageIO.read(src);
            setContents(image, src.getFile());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else {
        setContents(null, null);
    }
}
 
Example 12
@Override public Image getIcon() {
    if (icon == null && imageInByte != null) {
        try {
            final BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageInByte));
            icon = convertToFxImage(image);
            imageInByte = null;
        } catch (final Exception e) {
            ExceptionLogger.submitException(e);
        }
    }
    return icon;
}
 
Example 13
private static void verifyFileRead() throws IOException {
    File inputTestFile = createTestFile("inputTestFile");
    try {
        ImageIO.read(inputTestFile);
    } catch (IOException ex) {
        if (verifyInputExceptionMessage(ex))
            throw ex;
    } finally {
        inputTestFile.delete();
    }
}
 
Example 14
Source Project: sikuli-monkey   File: AndroidRobot.java    License: MIT License 5 votes vote down vote up
@Override
public ScreenImage captureScreen(Rectangle rect) {
    try {
        Debug.history("Take a screenshot from the device...");
        byte[] bytes = _device.takeSnapshot().convertToBytes(new PyObject[0], null); // PNG
        BufferedImage screen = ImageIO.read(new ByteArrayInputStream(bytes));
        BufferedImage part = screen.getSubimage(rect.x, rect.y, rect.width, rect.height);
        return new ScreenImage(rect, part);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source Project: common_gui_tools   File: GuiImagePanel.java    License: Apache License 2.0 5 votes vote down vote up
private void readImage(String imagePath) {
    try {
        image = ImageIO.read(new File(imagePath));
    } catch (IOException e) {
        GuiUtils.log(e);
    }
}
 
Example 16
Source Project: geoserver-shell   File: GeoserverCommands.java    License: MIT License 4 votes vote down vote up
@CliCommand(value = "geoserver getmap", help = "Get a map from the WMS service.")
public String getMap(
        @CliOption(key = "layers", mandatory = true, help = "The layers to display") String layers,
        @CliOption(key = "file", mandatory = false, unspecifiedDefaultValue = "map.png", help = "The file name") String fileName,
        @CliOption(key = "width", mandatory = false, help = "The width") String width,
        @CliOption(key = "height", mandatory = false, help = "The height") String height,
        @CliOption(key = "format", mandatory = false, help = "The format") String format,
        @CliOption(key = "srs", mandatory = false, help = "The srs") String srs,
        @CliOption(key = "bbox", mandatory = false, help = "The bbox") String bbox
) throws Exception {
    String url = geoserver.getUrl() + "/wms/reflect?layers=" + URLUtil.encode(layers);
    if (width != null) {
        url += "&width=" + width;
    }
    if (height != null) {
        url += "&height=" + height;
    }
    if (srs != null) {
        url += "&srs=" + srs;
    }
    if (bbox != null) {
        url += "&bbox=" + bbox;
    }
    String formatMimeType = "image/png";
    String formatImageIO = "png";
    if (format != null) {
        if (format.equalsIgnoreCase("jpeg") || format.equalsIgnoreCase("jpg")
                || format.equalsIgnoreCase("image/jpeg") || format.equalsIgnoreCase("image/jpg")) {
            formatMimeType = "image/jpeg";
            formatImageIO = "jpeg";
        }
        url += "&format=" + formatMimeType;
    }
    String message = fileName;
    BufferedImage image = ImageIO.read(new URL(url));
    if (image != null) {
        ImageIO.write(image, formatImageIO, new File(fileName));
    } else {
        message = "Unable to read URL (" + url + ")";
    }
    return message;
}
 
Example 17
Source Project: beautyeye   File: FileChooserDemo.java    License: Apache License 2.0 4 votes vote down vote up
public void loadFileInfo(File file) {
    boolean emptyPreview = true;

    if (file == null) {
        lbType.setText(null);
        lbSize.setText(null);
    } else {
        lbType.setText(externalChooser.getFileSystemView().getSystemTypeDescription(file));
        lbSize.setText(Long.toString(file.length()));

        String fileName = file.getName();

        int i = fileName.lastIndexOf(".");

        String ext = i < 0 ? null : fileName.substring(i + 1);

        FileType fileType = knownTypes.get(ext.toLowerCase());

        if (fileType != null) {
            switch (fileType) {
                case IMAGE:
                    try {
                        BufferedImage image = ImageIO.read(file);

                        double coeff = Math.min(((double) SIZE) / image.getWidth(),
                                ((double) SIZE) / image.getHeight());

                        BufferedImage scaledImage = new BufferedImage(
                                (int) Math.round(image.getWidth() * coeff),
                                (int) Math.round(image.getHeight() * coeff),
                                BufferedImage.TYPE_INT_RGB);

                        Graphics2D g = (Graphics2D) scaledImage.getGraphics();

                        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                        g.drawImage(image, 0, 0, scaledImage.getWidth(), scaledImage.getHeight(), null);

                        lbPreview.setText(null);
                        lbPreview.setIcon(new ImageIcon(scaledImage));

                        setComponent(lbPreview, 0, 1);

                        emptyPreview = false;
                    } catch (IOException e) {
                        // Empty preview
                    }

                    break;
            }
        }
    }

    if (emptyPreview) {
        lbPreview.setIcon(null);
        lbPreview.setText(resourceManager.getString("FileChooserDemo.preview.emptytext"));

        setComponent(lbPreview, 0, 1);
    }
}
 
Example 18
private void test(final ImageWriter writer) throws IOException {
    // Image initialization
    final BufferedImage imageWrite = new BufferedImage(WIDTH, HEIGHT,
                                                       TYPE_BYTE_BINARY);
    final Graphics2D g = imageWrite.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, WIDTH, HEIGHT);
    g.dispose();

    // File initialization
    final File file = File.createTempFile("temp", ".img");
    file.deleteOnExit();
    final FileOutputStream fos = new SkipWriteOnAbortOutputStream(file);
    final ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
    writer.setOutput(ios);
    writer.addIIOWriteProgressListener(this);

    // This write will be aborted, and file will not be touched
    writer.write(imageWrite);
    if (!isStartedCalled) {
        throw new RuntimeException("Started should be called");
    }
    if (!isProgressCalled) {
        throw new RuntimeException("Progress should be called");
    }
    if (!isAbortCalled) {
        throw new RuntimeException("Abort should be called");
    }
    if (isCompleteCalled) {
        throw new RuntimeException("Complete should not be called");
    }
    // Flush aborted data
    ios.flush();

    // This write should be completed successfully and the file should
    // contain correct image data.
    abortFlag = false;
    isAbortCalled = false;
    isCompleteCalled = false;
    isProgressCalled = false;
    isStartedCalled = false;
    writer.write(imageWrite);

    if (!isStartedCalled) {
        throw new RuntimeException("Started should be called");
    }
    if (!isProgressCalled) {
        throw new RuntimeException("Progress should be called");
    }
    if (isAbortCalled) {
        throw new RuntimeException("Abort should not be called");
    }
    if (!isCompleteCalled) {
        throw new RuntimeException("Complete should be called");
    }
    writer.dispose();
    ios.close();

    // Validates content of the file.
    final BufferedImage imageRead = ImageIO.read(file);
    for (int x = 0; x < WIDTH; ++x) {
        for (int y = 0; y < HEIGHT; ++y) {
            if (imageRead.getRGB(x, y) != imageWrite.getRGB(x, y)) {
                throw new RuntimeException("Test failed.");
            }
        }
    }
}
 
Example 19
public JAXBElement<Image> standardClassImage() throws IOException {
	Image image = ImageIO.read(getClass().getResourceAsStream("spring-ws.png"));
	return new JAXBElement<Image>(NAME, Image.class, image);
}
 
Example 20
public static BufferedImage loadCompatibleImage(URL resource)
        throws IOException {
    BufferedImage image = ImageIO.read(resource);
    return toCompatibleImage(image);
}