Java Code Examples for javax.imageio.ImageIO

The following are top voted examples for showing how to use javax.imageio.ImageIO. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: DWSurvey   File: TwoDimensionCode.java   View source code 9 votes vote down vote up
/**
 * 解析二维码(QRCode)
 * @param imgPath 图片路径
 * @return
 */
public String decoderQRCode(String imgPath) {
	// QRCode 二维码图片的文件
	File imageFile = new File(imgPath);
	BufferedImage bufImg = null;
	String content = null;
	try {
		bufImg = ImageIO.read(imageFile);
		QRCodeDecoder decoder = new QRCodeDecoder();
		content = new String(decoder.decode(new TwoDimensionCodeImage(bufImg)), "utf-8");
	} catch (IOException e) {
		System.out.println("Error: " + e.getMessage());
		e.printStackTrace();
	} catch (DecodingFailedException dfe) {
		System.out.println("Error: " + dfe.getMessage());
		dfe.printStackTrace();
	}
	return content;
}
 
Example 2
Project: trashjam2017   File: Splash.java   View source code 6 votes vote down vote up
/**
 * Create a new splash screen 
 */
Splash() {
	super(new Frame());
	
	FontData.setStatusListener(this);
	
	try {
		image = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("org/newdawn/slick/tools/hiero/resources/splash.png"));
		Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(400,250);
		setLocation((size.width - getWidth())/2, (size.height - getHeight()) / 2);
		setVisible(true);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 3
Project: geomapapp   File: XMap.java   View source code 6 votes vote down vote up
public void keyPressed(KeyEvent e) {
	if ( e.getKeyCode() == KeyEvent.VK_SPACE) {
		setSpaceBarPress(true);
	}

	if(getSpaceBarPress()) {
		// Set locations
		screenPressedX = MouseInfo.getPointerInfo().getLocation().x;
		screenPressedY = MouseInfo.getPointerInfo().getLocation().y;
		pressedX = scrollPane.getHorizontalScrollBar().getValue();
		pressedY = scrollPane.getVerticalScrollBar().getValue();

		// Set cursor to closed hand
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		ClassLoader loader = org.geomapapp.util.Icons.class.getClassLoader();
		String path = "org/geomapapp/resources/icons/close_hand.png";
		java.net.URL url = loader.getResource(path);
		try {
			BufferedImage im = ImageIO.read(url);
			Cursor closeHandCursor = toolkit.createCustomCursor( im, new Point(0,0), "close_hand");
			setCursor(closeHandCursor);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
 
Example 4
Project: omr-dataset-tools   File: SheetProcessor.java   View source code 6 votes vote down vote up
/**
 * Draw symbols boxes and None symbols locations on control image.
 *
 * @param controlPath target path for control image
 * @throws java.io.IOException in case of IO problem
 */
public void drawBoxes (Path controlPath)
        throws IOException
{
    BufferedImage ctrl = new BufferedImage(
            initialImg.getWidth(),
            initialImg.getHeight(),
            BufferedImage.TYPE_INT_RGB);
    Graphics2D g = ctrl.createGraphics();
    g.drawImage(initialImg, null, null);

    drawSymbols(annotations.getSymbols(), g);

    g.dispose();
    Files.createDirectories(controlPath.getParent());
    ImageIO.write(ctrl, OUTPUT_IMAGES_FORMAT, controlPath.toFile());
}
 
Example 5
Project: SudoTimer   File: MainViewController.java   View source code 6 votes vote down vote up
public void takePic() {
	// get default webcam and open it
	Webcam webcam = Webcam.getDefault();

	Dimension[] nonStandardResolutions = new Dimension[] { WebcamResolution.PAL.getSize(),
			WebcamResolution.HD720.getSize(), new Dimension(2000, 1000), new Dimension(1000, 500), };
	webcam.setCustomViewSizes(nonStandardResolutions);
	webcam.setViewSize(WebcamResolution.HD720.getSize());
	webcam.open();

	// get image
	BufferedImage image = webcam.getImage();

	// save image to PNG file
	try {
		ImageIO.write(image, "PNG", new File("src/capture/test.png"));
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	webcam.close();
}
 
Example 6
Project: renren-fast   File: SysLoginController.java   View source code 6 votes vote down vote up
@RequestMapping("captcha.jpg")
public void captcha(HttpServletResponse response)throws ServletException, IOException {
	response.setHeader("Cache-Control", "no-store, no-cache");
	response.setContentType("image/jpeg");

	//生成文字验证码
	String text = producer.createText();
	//生成图片验证码
	BufferedImage image = producer.createImage(text);
	//保存到shiro session
	ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

	ServletOutputStream out = response.getOutputStream();
	ImageIO.write(image, "jpg", out);
	IOUtils.closeQuietly(out);
}
 
Example 7
Project: McHeliPrivacyShield   File: MCH_MultiplayClient.java   View source code 6 votes vote down vote up
@CoreInvoke
public static void startSendImageData() {
	Log.log.warn("sending screenshot is requested!");
	try {
		final ScreenShotShieldEvent.Pre eventPre = new ScreenShotShieldEvent.Pre(Config.getConfig().ssmode.get());
		eventPre.post();
		if (!eventPre.isCanceled()) {
			final ScreenShotShieldEvent.Post eventPost = new ScreenShotShieldEvent.Post(Config.getConfig().ssmode.get());
			eventPost.pending = ScreenShotShieldRegistery.onRequested(Config.getConfig().ssmode.get());
			eventPost.post();
			if (!eventPost.isCanceled())
				if (eventPost.pending!=null) {
					dataOutputStream = new MCH_OStream();
					ImageIO.write(eventPost.pending, "png", dataOutputStream);
				}
		}
	} catch (final Exception arg7) {
		Log.log.error("Failed to send image: ", arg7);
	}

}
 
Example 8
Project: jaer   File: MotionViewer.java   View source code 6 votes vote down vote up
synchronized void writeMovieFrame() {
    try {
        Container container = getContentPane();
        canvas = chip.getCanvas().getCanvas();
        Rectangle r = canvas.getBounds();
        Image image = canvas.createImage(r.width, r.height);
        Graphics g = image.getGraphics();
        synchronized (container) {
            container.paintComponents(g);
            if (chip.getCanvas().getImageOpenGL() != null) {
                ImageIO.write(chip.getCanvas().getImageOpenGL(), "png", new File(sequenceDir, getFilename()));
            }
        }
        frameNumber++;
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}
 
Example 9
Project: automat   File: QrcodeUtil.java   View source code 6 votes vote down vote up
public static String createQrcode(String dir, String _text) {
	String qrcodeFilePath = "";
	try {
		int qrcodeWidth = 300;
		int qrcodeHeight = 300;
		String qrcodeFormat = "png";
		HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		BitMatrix bitMatrix = new MultiFormatWriter().encode(_text, BarcodeFormat.QR_CODE, qrcodeWidth,
				qrcodeHeight, hints);

		BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
		File qrcodeFile = new File(dir + "/" + UUID.randomUUID().toString() + "." + qrcodeFormat);
		ImageIO.write(image, qrcodeFormat, qrcodeFile);
		MatrixToImageWriter.writeToPath(bitMatrix, qrcodeFormat, qrcodeFile.toPath());
		qrcodeFilePath = qrcodeFile.getAbsolutePath();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return qrcodeFilePath;
}
 
Example 10
Project: litiengine   File: ImageSerializer.java   View source code 6 votes vote down vote up
public static BufferedImage loadImage(final String fileName) {
  final File file = new File(fileName);
  if (!file.exists()) {
    return null;
  }

  BufferedImage img;
  try {
    img = ImageIO.read(file);
    if (img == null) {
      return null;
    }

    final BufferedImage compatibleImg = ImageProcessing.getCompatibleImage(img.getWidth(), img.getHeight());
    compatibleImg.createGraphics().drawImage(img, 0, 0, null);
    compatibleImg.createGraphics().dispose();

    return compatibleImg;
  } catch (final Exception e) {
    log.log(Level.SEVERE, e.getMessage(), e);
    return null;
  }
}
 
Example 11
Project: openjdk-jdk10   File: OpaquePNGToGIFTest.java   View source code 6 votes vote down vote up
public void createAnimatedImage(BufferedImage bi, IIOMetadata metadata,
        ImageWriter writer, File outputFile) {
    try {

        fos = new FileOutputStream(outputFile);
        ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
        System.out.println(ios);
        writer.setOutput(ios);

        ImageWriteParam param = writer.getDefaultWriteParam();
        IIOMetadata streamData = writer.getDefaultStreamMetadata(param);

        writer.prepareWriteSequence(streamData);
        ImageTypeSpecifier specify = new ImageTypeSpecifier(bi);
        IIOMetadata imgData = writer.convertImageMetadata(
                (IIOMetadata) metadata, specify, param);
        GIFImageMetadata gifData = setAnimationProperties(imgData);
        IIOImage iim = new IIOImage(bi, null, gifData);
        param.setProgressiveMode(param.MODE_DISABLED);
        writer.writeToSequence(iim, param);
        writer.endWriteSequence();
        ios.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 12
Project: xmanager   File: CaptchaUtils.java   View source code 6 votes vote down vote up
/**
 * 生成验证码
 */
static void generate(HttpServletResponse response, String vCode) {
	BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
	response.setHeader("Pragma","no-cache");
	response.setHeader("Cache-Control","no-cache");
	response.setDateHeader("Expires", 0);
	response.setContentType("image/jpeg");
	
	ServletOutputStream sos = null;
	try {
		drawGraphic(image, vCode);
		sos = response.getOutputStream();
		ImageIO.write(image, "JPEG", sos);
		sos.flush();
	} catch (Exception e) {
		throw new RuntimeException(e);
	} finally {
		IOUtils.closeQuietly(sos);
	}
}
 
Example 13
Project: sbc-qsystem   File: WysiwygDlg.java   View source code 6 votes vote down vote up
private WysiwygDlg(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    initComponents();
    setDefaultCloseOperation(HIDE_ON_CLOSE);
    try {
        setIconImage(ImageIO
            .read(FAdmin.class
                .getResource("/ru/apertum/qsystem/client/forms/resources/admin.png")));
    } catch (IOException ex) {
        System.err.println(ex);
    }

    panel.removeAll();
    javafxPanel = new JFXPanel();
    Platform.runLater(() -> {
        htmlEditor = new HTMLEditor();
        Scene scene = new Scene(htmlEditor, 750, 500, Color.web("#666970"));
        javafxPanel.setScene(scene);
    });
    final GridLayout gl = new GridLayout(1, 1);
    panel.setLayout(gl);
    panel.add(javafxPanel);
}
 
Example 14
Project: geomapapp   File: Cursors.java   View source code 6 votes vote down vote up
public static Cursor getCursor( int which ) {
	Cursor c = (Cursor) cursorCache.get(new Integer(which));
	if (c != null) return c;

	try {
		ClassLoader loader = org.geomapapp.util.Icons.class.getClassLoader();
		String path = "org/geomapapp/resources/icons/" +names[which];
		java.net.URL url = loader.getResource(path);
		BufferedImage im = ImageIO.read(url);
		String name = names[which].substring(0, names[which].lastIndexOf("."));
		System.out.println(im.getWidth() + "\t" + im.getHeight());
		
		c = Toolkit.getDefaultToolkit().createCustomCursor(im, new Point(hotSpot[which][0],hotSpot[which][1]), name);
		cursorCache.put(new Integer(which), c);
		return c;
	} catch(Exception ex) {
		return Cursor.getDefaultCursor();
	}
}
 
Example 15
Project: jdk8u-jdk   File: GifTransparencyTest.java   View source code 6 votes vote down vote up
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 16
Project: Progetto-C   File: Splash.java   View source code 6 votes vote down vote up
/**
 * Create a new splash screen 
 */
Splash() {
	super(new Frame());
	
	FontData.setStatusListener(this);
	
	try {
		image = ImageIO.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("org/newdawn/slick/tools/hiero/resources/splash.png"));
		Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
		setSize(400,250);
		setLocation((size.width - getWidth())/2, (size.height - getHeight()) / 2);
		setVisible(true);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 17
Project: Lithium-Forge   File: ImageManager.java   View source code 6 votes vote down vote up
@SideOnly(Side.CLIENT)
public static void handleImage(LImage img) {
	if (isImageHandled(img)) {
		return;
	}
	try {
		LithiumMod.log("Loading image for control with UUID[" + img.getUUID() + "].");
		handledControls.add(img.getUUID());
		bufferedImages.put(img.getUUID(), new DynamicTexture(ImageIO.read(new URL(img.getImageURL()))));
		LithiumMod.log("Finished loading image for control with UUID[" + img.getUUID() + "].");

	} catch (IOException e) {
		LithiumMod.log("An error occured while trying to load image for control with UUID[" + img.getUUID() + "].");
		e.printStackTrace();
	}
}
 
Example 18
Project: incubator-netbeans   File: ScreenshotComponent.java   View source code 6 votes vote down vote up
@Override
public void save() throws IOException {
    FileChooserBuilder fchb = new FileChooserBuilder(ScreenshotComponent.class);
    String[] writerFileSuffixes = ImageIO.getWriterFileSuffixes();
    fchb.setFileFilter(new FileNameExtensionFilter(Bundle.CTL_ImageFiles(), writerFileSuffixes));
    File file = fchb.showSaveDialog();
    if (file != null) {
        if (file.exists()) {
            NotifyDescriptor nd = new NotifyDescriptor.Confirmation(Bundle.MSG_Overwrite(file.getName()), toString());
            Object doOverwrite = DialogDisplayer.getDefault().notify(nd);
            if (!NotifyDescriptor.YES_OPTION.equals(doOverwrite)) {
                return ;
            }
        }
        canvas.save(file);
    }
}
 
Example 19
Project: courier   File: Main.java   View source code 6 votes vote down vote up
public static void main(String... args) {
    invisible = new JFrame();
    try {
        invisible.setIconImage(ImageIO.read(FileUtil.getResource("icon.png")));
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Our discord-rpc library doesn't support macOS yet
    if (!SystemTray.isSupported() || !Desktop.isDesktopSupported() || SystemUtils.IS_OS_MAC_OSX) { // We do this because if there is no sys-tray icon users can't terminate the program, which would be bad
        JOptionPane.showMessageDialog(null, "Your platform isn't supported currently!", "Unsupported platform!", JOptionPane.ERROR_MESSAGE);
        return;
    }

    new Courier();
}
 
Example 20
Project: SE2017-Team1   File: Main.java   View source code 6 votes vote down vote up
public static BufferedImage callVisualizationGroup (Graph graph)
{
    System.out.println("<debug> Attempting to call visualization..");
    
    try
    {
    	return (ImageIO.read(new File("C:\\Users\\USER\\Desktop\\x\\penguin.jpg")));
    }
    catch (Exception e)
    {
    }
    try{
    	return (ImageIO.read(new File("penguin.jpg")));
    }
    catch (Exception ex){
    	System.out.println("<debug> Exception caught..");
        return (null);
    }
}
 
Example 21
Project: incubator-netbeans   File: ImageCacheTest.java   View source code 6 votes vote down vote up
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    
    fd.show(true);
    if (fd.getDirectory() != null && fd.getFile() != null) {
        String filename = fd.getDirectory() + fd.getFile();
        try {
            File f = new File(filename);
            BufferedImage img = ImageIO.read(f);
            imgs.add (filename);
            ImagePanel ip = new ImagePanel(img);
            ip.setName (filename);
            System.err.println("Created " + ip);
            jTabbedPane1.insertTab(f.getName(), null, new JScrollPane(ip), filename, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 22
Project: HotaruFX   File: RenderTask.java   View source code 6 votes vote down vote up
@Override
protected Boolean call() throws Exception {
    val fxTimeline = timeLine.getFxTimeline();

    val totalFrames = toFrame(fxTimeline.getTotalDuration());
    int frame = 0;
    while (frame < totalFrames) {
        updateProgress(frame, totalFrames);
        updateMessage(String.format("%d / %d", frame + 1, totalFrames));
        fxTimeline.jumpTo(toDuration(frame));

        val image = newImage();

        val latch = new CountDownLatch(1);
        Platform.runLater(() -> {
            scene.snapshot(image);
            latch.countDown();
        });
        latch.await();

        val file = new File(directory, String.format("frame_%05d.png", frame + 1));
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
        frame++;
    }
    return Boolean.TRUE;
}
 
Example 23
Project: NoMoreOversleeps   File: WebcamData.java   View source code 6 votes vote down vote up
@Override
public void webcamImageObtained(WebcamEvent we)
{
	if (this.image == null)
	{
		return;
	}
	try
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ImageIO.write(this.image, "JPG", baos);
		byte[] data = baos.toByteArray();
		this.imageBase64 = new String(Base64.getEncoder().encode(data), "UTF8");
	}
	catch (IOException e)
	{
		log.error(e.getMessage(), e);
	}
}
 
Example 24
Project: jdk8u-jdk   File: CanDecodeTest.java   View source code 6 votes vote down vote up
public void doTest(ImageReaderSpi spi) throws IOException {
    System.out.println("Test for " + title +
            (canDecode ? " (can decode)" : " (can't decode)"));
    System.out.print("As a stream...");
    ImageInputStream iis =
            ImageIO.createImageInputStream(getDataStream());

    if (spi.canDecodeInput(iis) != canDecode) {
        throw new RuntimeException("Test failed: wrong decideion " +
                "for stream data");
    }
    System.out.println("OK");

    System.out.print("As a file...");
    iis = ImageIO.createImageInputStream(getDataFile());
    if (spi.canDecodeInput(iis) != canDecode) {
        throw new RuntimeException("Test failed: wrong decideion " +
                "for file data");
    }
    System.out.println("OK");
}
 
Example 25
Project: twainBDirect   File: BoshScanListener.java   View source code 6 votes vote down vote up
private void normalImageFormatWrite(String type) {
    try {
        System.out.println(type + " ouput");
        //--
        File fileOutputFolder = new File(PATH + OUT_PUT_FILE_NAME + generateNewId() + "." + type);
        //--
        image = ImageManager.convertBuferredImageType(image, BufferedImage.TYPE_INT_RGB);
        //--
        if (image == null) {
            FatherTree.createNewLogFile(fatherTree.getCurrentFolder(), "una de las imagenes escaneadas no pudo ser adquirida");
        } else {
            if (!ImageIO.write(image, type, fileOutputFolder)) {
                FatherTree.createNewLogFile(fatherTree.getCurrentFolder(), "Ocurrio un error al intentar escribir el archivo");
            }
        }
    } catch (Exception e) {
    }
}
 
Example 26
Project: libgdx_ui_editor   File: ImageUtils.java   View source code 6 votes vote down vote up
public BufferedImage extractImage(TextureAtlas.TextureAtlasData atlas, String regionName, int[] splits) {
    for (TextureAtlas.TextureAtlasData.Region region : atlas.getRegions()) {
        if(region.name.equals(regionName)) {
            TextureAtlas.TextureAtlasData.Page page = region.page;
            BufferedImage img = null;
            try {
                img = ImageIO.read(page.textureFile.file());
            } catch (IOException e) {

            }
            region.splits = splits;
            return extractNinePatch(img, region);
        }
    }
    return null;
}
 
Example 27
Project: betaexpansion   File: TextureCompassFX.java   View source code 6 votes vote down vote up
public TextureCompassFX(Minecraft minecraft)
{
    super(Item.compass.getIconFromDamage(0));
    isCustom = true;
    mc = minecraft;
    res = (Integer)mc.renderEngine.textureSizeIdMap.get(mc.renderEngine.getTexture("/gui/items.png"))/16;
    compassIconImageData = new int[res*res];
    imageData = new byte[res*res*4];
    tileImage = 1;
    try
    {
        BufferedImage bufferedimage = ImageIO.read(mc.texturePackList.selectedTexturePack.getResourceAsStream("/gui/items.png"));
        int i = (iconIndex % 16) * res;
        int j = (iconIndex / 16) * res;
        bufferedimage.getRGB(i, j, res, res, compassIconImageData, 0, res);
    }
    catch(IOException ioexception)
    {
        ioexception.printStackTrace();
    }
}
 
Example 28
Project: octoBubbles   File: AbstractDiagramController.java   View source code 5 votes vote down vote up
public void handleMenuActionImage(){
    try{
        WritableImage image = getSnapShot();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Save Image");
        File output = fileChooser.showSaveDialog(getStage());
        ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", output);
    } catch (IOException ex) {
        Logger.getLogger(AbstractDiagramController.class.getName()).log(Level.SEVERE, null, ex);
    }
}
 
Example 29
Project: raven   File: ImageUtils.java   View source code 5 votes vote down vote up
private static String getImageFormatName(final byte[] imageBytes)
		throws IOException {
	ByteArrayInputStream input = new ByteArrayInputStream(imageBytes);
	ImageInputStream imageInput = ImageIO.createImageInputStream(input);
	Iterator<ImageReader> iterator = ImageIO.getImageReaders(imageInput);
	String imageFormatName = null;
	if (iterator.hasNext()) {
		ImageReader reader = iterator.next();
		imageFormatName = reader.getFormatName().toUpperCase();
	}

	try {
		return imageFormatName;
	} finally {
		if (imageInput != null) {
			imageInput.close();
		}
	}
}
 
Example 30
Project: Clipcon-Server   File: MessageParser.java   View source code 5 votes vote down vote up
private static byte[] getImgBytes(Image image) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	try {
		ImageIO.write(toBufferedImage(image), "png", baos);
	} catch (IOException ex) {
		// handle it here.... not implemented yet...
	}
	return baos.toByteArray();
}
 
Example 31
Project: OOPIter2   File: TileDrawingVisitor.java   View source code 5 votes vote down vote up
@Override
public void visitNormal(Normal normal) {
    BufferedImage texture = null;
	try {
		texture = ImageIO.read(new File("src/application/images/terrain/Grass.png"));
	} catch (IOException e) {
           try {
               texture = ImageIO.read(new File("../src/application/images/terrain/Grass.png"));
           } catch (IOException e2) {
               e2.printStackTrace();
           }		}
       texture = resizeImage(texture);
	addToPriorityQueue(TERRAIN, texture);
}
 
Example 32
Project: lams   File: BufferedImageHttpMessageConverter.java   View source code 5 votes vote down vote up
/**
 * Sets the default {@code Content-Type} to be used for writing.
 * @throws IllegalArgumentException if the given content type is not supported by the Java Image I/O API
 */
public void setDefaultContentType(MediaType defaultContentType) {
	Assert.notNull(defaultContentType, "'contentType' must not be null");
	Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByMIMEType(defaultContentType.toString());
	if (!imageWriters.hasNext()) {
		throw new IllegalArgumentException(
				"Content-Type [" + defaultContentType + "] is not supported by the Java Image I/O API");
	}

	this.defaultContentType = defaultContentType;
}
 
Example 33
Project: easyweb   File: ValidateCodeServlet.java   View source code 5 votes vote down vote up
private void createImage(HttpServletRequest request,
		HttpServletResponse response) throws IOException {
	
	response.setHeader("Pragma", "no-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", 0);
	response.setContentType("image/jpeg");
	
	/*
	 * 得到参数高,宽,都为数字时,则使用设置高宽,否则使用默认值
	 */
	String width = request.getParameter("width");
	String height = request.getParameter("height");
	if (StringUtils.isNumeric(width) && StringUtils.isNumeric(height)) {
		w = NumberUtils.toInt(width);
		h = NumberUtils.toInt(height);
	}
	
	BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
	Graphics g = image.getGraphics();

	/*
	 * 生成背景
	 */
	createBackground(g);

	/*
	 * 生成字符
	 */
	String s = createCharacter(g);
	request.getSession().setAttribute(VALIDATE_CODE, s);

	g.dispose();
	OutputStream out = response.getOutputStream();
	ImageIO.write(image, "JPEG", out);
	out.close();

}
 
Example 34
Project: OpenJSharp   File: OutputTests.java   View source code 5 votes vote down vote up
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    OutputType t = (OutputType)env.getModifier(generalDestRoot);
    outputType = t.getType();
}
 
Example 35
Project: openjdk-jdk10   File: ImageDataContentHandler.java   View source code 5 votes vote down vote up
public ImageDataContentHandler() {
    String[] mimeTypes = ImageIO.getReaderMIMETypes();
    flavor = new DataFlavor[mimeTypes.length];
    for(int i=0; i < mimeTypes.length; i++) {
        flavor[i] = new ActivationDataFlavor(
            java.awt.Image.class, mimeTypes[i], "Image");
    }
}
 
Example 36
Project: ChessBot   File: ImageUtils.java   View source code 5 votes vote down vote up
public static void writeImage(String path, String moveNumber, String fileName, BufferedImage image){
    try{
        ImageIO.write(image, IMAGE_MIME_TYPE, new FileOutputStream(path + "\\" + fileName + moveNumber + "." + IMAGE_MIME_TYPE));
    }catch(Exception e) {
        UIUtils.popupError(e, "ImageUtils::writeImage");
    }
}
 
Example 37
Project: ostracker   File: FileUtil.java   View source code 5 votes vote down vote up
public static void writeImage(RenderedImage image, String fileFormat, File file) {
    int timesAttempted = 0;

    do {
        try {
            ImageIO.write(image, fileFormat, file);
            break;
        } catch (Exception e) {
            e.printStackTrace();
        }
    } while (timesAttempted++ < TIMES_TO_ATTEMPT_WRITING_IMAGE);
}
 
Example 38
Project: openjdk-jdk10   File: IncorrectFractionalClip.java   View source code 5 votes vote down vote up
private static void validate(final BufferedImage bi, BufferedImage gold,
                             final int testID) throws Exception {
    for (int x = 0; x < SIZE; ++x) {
        for (int y = 0; y < SIZE; ++y) {
            int rgb = bi.getRGB(x, y);
            int goldRGB = gold.getRGB(x, y);
            if ((rgb != GREEN.getRGB() && rgb != RED.getRGB())
                    || rgb != goldRGB) {
                ImageIO.write(bi, "png", new File("image.png"));
                ImageIO.write(gold, "png", new File("gold.png"));
                throw new RuntimeException("Test failed.");
            }
        }
    }
}
 
Example 39
Project: GIFKR   File: JPEGFilter.java   View source code 5 votes vote down vote up
@Override
public BufferedImage apply(BufferedImage img) {

	if(compressionLevel == 0f)
		return img;
	
	try {
		ImageWriter iw = ImageIO.getImageWritersByFormatName("jpeg").next();
		JPEGImageWriteParam iwp = (JPEGImageWriteParam) iw.getDefaultWriteParam();
		iwp.setOptimizeHuffmanTables(false);
		iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
		iwp.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
		iwp.setCompressionQuality(1f-compressionLevel);


		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		iw.setOutput(new MemoryCacheImageOutputStream(baos)); 

		IIOImage outputImage = new IIOImage(img, null, null);
		iw.write(null, outputImage, iwp);
		iw.dispose();
		
		baos.flush(); 
		byte[] returnImage = baos.toByteArray(); 
		baos.close();
		
		
		BufferedImage img2 = ImageIO.read(new ByteArrayInputStream(returnImage));
		
		if(img2 == null)
			throw new Exception();
		else
			img = img2;

	} catch (Exception e) {
		e.printStackTrace();
	}

	return img;
}
 
Example 40
Project: allure-java   File: Stepdefs.java   View source code 5 votes vote down vote up
@Attachment(type = "image/png", fileExtension = "png", value = "att")
public byte[] attach() {
    try {
        BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        baos.flush();
        byte[] imageInByte = baos.toByteArray();
        baos.close();
        return imageInByte;
    } catch (AWTException | IOException e) {
        return null;
    }
}