javax.imageio.ImageIO Java Examples

The following examples show how to use javax.imageio.ImageIO. 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: JpegToPngRenditionProvider.java    From spring-content with Apache License 2.0 8 votes vote down vote up
@Override
public InputStream convert(InputStream fromInputSource, String toMimeType) {
	try {
		// read a jpeg from a inputFile
		BufferedImage bufferedImage = ImageIO.read(fromInputSource);

		// write the bufferedImage back to outputFile
		ImageIO.write(bufferedImage, "png", new File("/tmp/temp.png"));

		return new FileInputStream("/tmp/temp.png");
	}
	catch (Exception e) {
		e.printStackTrace();
	}
	finally {
		IOUtils.closeQuietly(fromInputSource);
	}
	return null;
}
 
Example #2
Source File: DrawRotatedStringUsingRotatedFont.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks an image color. RED and GREEN are allowed only.
 */
private static void checkColors(final BufferedImage bi1,
                                final BufferedImage bi2)
        throws IOException {
    for (int i = 0; i < SIZE; ++i) {
        for (int j = 0; j < SIZE; ++j) {
            final int rgb1 = bi1.getRGB(i, j);
            final int rgb2 = bi2.getRGB(i, j);
            if (rgb1 != rgb2 || rgb1 != 0xFFFF0000 && rgb1 != 0xFF00FF00) {
                ImageIO.write(bi1, "png", new File("image1.png"));
                ImageIO.write(bi2, "png", new File("image2.png"));
                throw new RuntimeException("Failed: wrong text location");
            }
        }
    }
}
 
Example #3
Source File: GuiModListScroll.java    From CodeChickenCore with MIT License 6 votes vote down vote up
private static void screenshotStencil(int x) {
    Dimension d = GuiDraw.displayRes();
    ByteBuffer buf = BufferUtils.createByteBuffer(d.width * d.height);
    BufferedImage img = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);

    glPixelStorei(GL_PACK_ALIGNMENT, 1);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glReadPixels(0, 0, d.width, d.height, GL_STENCIL_INDEX, GL_UNSIGNED_BYTE, buf);
    for(int i = 0; i < d.width; i++)
        for(int j = 0; j < d.height; j++)
            img.setRGB(i, d.height-j-1, buf.get(j * d.width + i) == 0 ? 0 : 0xFFFFFF);
    try {
        ImageIO.write(img, "png", new File("stencil"+x+".png"));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #4
Source File: ImageUtil.java    From xnx3 with Apache License 2.0 6 votes vote down vote up
/**
   * 等比例缩放
   * <br/>判断图像的宽度,若是宽度大于传入的值,则进行等比例压缩到指定宽高。若是图片小于指定的值,则不处理
   * @param inputStream 原图
   * @param maxWidth 缩放后的宽度。若大于这个宽度才会进行等比例缩放。否则不进行处理。传入0则不处理,忽略
   * @param suffix 图片的后缀名,如png、jpg
   * @return 处理好的
   */
  public static InputStream proportionZoom(InputStream inputStream,int maxWidth,String suffix){
  	if(inputStream == null){
  		return null;
  	}
  	if(maxWidth == 0 || maxWidth < 0){
  		return inputStream;
  	}
  	
  	try {
	BufferedImage bi = ImageIO.read(inputStream);
	BufferedImage b = proportionZoom(bi, maxWidth);
	ByteArrayOutputStream os = new ByteArrayOutputStream();  
	ImageIO.write(b, suffix, os);  
	InputStream is = new ByteArrayInputStream(os.toByteArray()); 
	return is;
} catch (IOException e) {
	e.printStackTrace();
}
  	return null;
  }
 
Example #5
Source File: EncodeSubImageTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    if (args.length > 0) {
        format = args[0];
    }

    writer = ImageIO.getImageWritersByFormatName(format).next();

    file_suffix =writer.getOriginatingProvider().getFileSuffixes()[0];

    BufferedImage src = createTestImage();
    EncodeSubImageTest m1 = new EncodeSubImageTest(src);
    m1.doTest("test_src");

    BufferedImage sub = src.getSubimage(subImageOffset, subImageOffset,
            src.getWidth() - 2 * subImageOffset,
            src.getHeight() - 2 * subImageOffset);
    EncodeSubImageTest m2 = new EncodeSubImageTest(sub);
    m2.doTest("test_sub");
}
 
Example #6
Source File: ImageHelper.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static byte[] getImageBytes(Image image, String type) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    BufferedImage bufImage = convertToBufferedImage(image);
    ImageWriter writer = null;
    Iterator<ImageWriter> i = ImageIO.getImageWritersByMIMEType(type);
    if (i.hasNext()) {
        writer = i.next();
    }
    if (writer != null) {
        ImageOutputStream stream = null;
        stream = ImageIO.createImageOutputStream(baos);
        writer.setOutput(stream);
        writer.write(bufImage);
        stream.close();
        return baos.toByteArray();
    }
    return null;
}
 
Example #7
Source File: IconEditor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static NbImageIcon iconFromResourceName(String resName, FileObject srcFile) {
    ClassPath cp = ClassPath.getClassPath(srcFile, ClassPath.SOURCE);
    FileObject fo = cp.findResource(resName);
    if (fo == null) {
        cp = ClassPath.getClassPath(srcFile, ClassPath.EXECUTE);
        fo = cp.findResource(resName);
    }
    if (fo != null) {
        try {
            try {
                Image image = ImageIO.read(fo.getURL());
                if (image != null) { // issue 157546
                    return new NbImageIcon(TYPE_CLASSPATH, resName, new ImageIcon(image));
                }
            } catch (IllegalArgumentException iaex) { // Issue 178906
                Logger.getLogger(IconEditor.class.getName()).log(Level.INFO, null, iaex);
                return new NbImageIcon(TYPE_CLASSPATH, resName, new ImageIcon(fo.getURL()));
            }
        } catch (IOException ex) { // should not happen
            Logger.getLogger(IconEditor.class.getName()).log(Level.WARNING, null, ex);
        }
    }
    return null;
}
 
Example #8
Source File: ImageUtils.java    From jpress with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static void zoom(int maxWidth, String srcImageFile, String destImageFile) {
    try {
        BufferedImage srcImage = ImageIO.read(new File(srcImageFile));
        int srcWidth = srcImage.getWidth();
        int srcHeight = srcImage.getHeight();

        // 当宽度在 maxWidth 范围之内,直接copy
        if (srcWidth <= maxWidth) {
            FileUtils.copyFile(new File(srcImageFile), new File(destImageFile));
        }
        // 当宽度超出 maxWidth 范围,将宽度变为 maxWidth,高度按比例缩放
        else {
            float scalingRatio = (float) maxWidth / (float) srcWidth;            // 计算缩放比率
            float maxHeight = ((float) srcHeight * scalingRatio);    // 计算缩放后的高度
            BufferedImage ret = resize(srcImage, maxWidth, (int) maxHeight);
            save(ret, destImageFile);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #9
Source File: SunJPEGEncoderAdapter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Encodes an image in JPEG format and writes it to an output stream.
 *
 * @param bufferedImage  the image to be encoded (<code>null</code> not
 *     permitted).
 * @param outputStream  the OutputStream to write the encoded image to
 *     (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O problem.
 * @throws NullPointerException if <code>bufferedImage</code> is
 *     <code>null</code>.
 */
public void encode(BufferedImage bufferedImage, OutputStream outputStream)
        throws IOException {
    if (bufferedImage == null) {
        throw new IllegalArgumentException("Null 'image' argument.");
    }
    if (outputStream == null) {
        throw new IllegalArgumentException("Null 'outputStream' argument.");
    }
    Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter writer = (ImageWriter) iterator.next();
    ImageWriteParam p = writer.getDefaultWriteParam();
    p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    p.setCompressionQuality(this.quality);
    ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
    writer.setOutput(ios);
    writer.write(null, new IIOImage(bufferedImage, null, null), p);
    ios.flush();
    writer.dispose();
    ios.close();
}
 
Example #10
Source File: EvolvingImagesCmd.java    From jenetics with Apache License 2.0 6 votes vote down vote up
static void writeImage(
	final File file,
	final PolygonChromosome chromosome,
	final int width,
	final int height
) {
	final double MIN_SIZE = 500;
	final double scale = max(max(MIN_SIZE/width, MIN_SIZE/height), 1.0);
	final int w = (int)round(scale*width);
	final int h = (int)round(scale*height);

	try {
		final BufferedImage image = new BufferedImage(w, h, TYPE_INT_ARGB);
		final Graphics2D graphics = image.createGraphics();
		chromosome.draw(graphics, w, h);

		ImageIO.write(image, "png", file);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}
 
Example #11
Source File: GifWriter.java    From scrimage with Apache License 2.0 6 votes vote down vote up
@Override
    public void write(AwtImage image, ImageMetadata metadata, OutputStream out) throws IOException {

        javax.imageio.ImageWriter writer = ImageIO.getImageWritersByFormatName("gif").next();
        ImageWriteParam params = writer.getDefaultWriteParam();

        if (progressive) {
            params.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
        } else {
            params.setProgressiveMode(ImageWriteParam.MODE_DISABLED);
        }

        try (MemoryCacheImageOutputStream output = new MemoryCacheImageOutputStream(out)) {
            writer.setOutput(output);
            writer.write(null, new IIOImage(image.awt(), null, null), params);
            writer.dispose();
        }

//        IOUtils.closeQuietly(out);
    }
 
Example #12
Source File: JpegDataContentHandler.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * return the Transfer Data of type DataFlavor from InputStream
 * @param df The DataFlavor.
 * @param ins The InputStream corresponding to the data.
 * @return The constructed Object.
 */
public Object getTransferData(DataFlavor df, DataSource ds) {

    // this is sort of hacky, but will work for the
    // sake of testing...
    if (df.getMimeType().startsWith("image/jpeg")) {
        if (df.getRepresentationClass().getName().equals(STR_SRC)) {
            InputStream inputStream = null;
            BufferedImage jpegLoadImage = null;

            try {
                inputStream = ds.getInputStream();
                jpegLoadImage = ImageIO.read(inputStream);

            } catch (Exception e) {
                System.out.println(e);
            }

            return jpegLoadImage;
        }
    }
    return null;
}
 
Example #13
Source File: MergeStdCommentTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    String format = "javax_imageio_1.0";
    BufferedImage img =
        new BufferedImage(16, 16, BufferedImage.TYPE_INT_RGB);
    ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
    IIOMetadata meta =
        iw.getDefaultImageMetadata(new ImageTypeSpecifier(img), null);
    DOMImplementationRegistry registry;
    registry = DOMImplementationRegistry.newInstance();
    DOMImplementation impl = registry.getDOMImplementation("XML 3.0");
    Document doc = impl.createDocument(null, format, null);
    Element root, text, entry;
    root = doc.getDocumentElement();
    root.appendChild(text = doc.createElement("Text"));
    text.appendChild(entry = doc.createElement("TextEntry"));
    // keyword isn't #REQUIRED by the standard metadata format.
    // However, it is required by the PNG format, so we include it here.
    entry.setAttribute("keyword", "Comment");
    entry.setAttribute("value", "Some demo comment");
    meta.mergeTree(format, root);
}
 
Example #14
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an image of what currently is drawn on the canvas.
 * <p/>
 * Throws an {@link ActivitiException} when {@link #close()} is already
 * called.
 */
public InputStream generateImage(String imageType) {
    if (closed) {
        throw new ActivitiException("ProcessDiagramGenerator already closed");
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        // Try to remove white space
        minX = (minX <= 5) ? 5 : minX;
        minY = (minY <= 5) ? 5 : minY;
        BufferedImage imageToSerialize = processDiagram;
        if (minX >= 0 && minY >= 0) {
            imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
        }
        ImageIO.write(imageToSerialize, imageType, out);
    } catch (IOException e) {
        throw new ActivitiException("Error while generating process image", e);
    } finally {
        IoUtil.closeSilently(out);
    }
    return new ByteArrayInputStream(out.toByteArray());
}
 
Example #15
Source File: KMeansTest.java    From pyramid with Apache License 2.0 6 votes vote down vote up
private static void plot(Vector vector, int height, int width, String imageFile) throws Exception{

        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//        Graphics2D g2d = image.createGraphics();
//        g2d.setBackground(Color.WHITE);
//
//
//        g2d.fillRect ( 0, 0, image.getWidth(), image.getHeight() );
//        g2d.dispose();
        for (int i=0;i<width;i++){
            for (int j=0;j<height;j++){
                int v = (int)(vector.get(i*width+j));
                int rgb = 65536 * v + 256 * v + v;
                image.setRGB(j,i,rgb);
//                image.setRGB(j,i,(int)(vector.get(i*width+j)/255*16777215));
            }
        }


        new File(imageFile).getParentFile().mkdirs();
        ImageIO.write(image,"png",new File(imageFile));
    }
 
Example #16
Source File: WelcomePanel.java    From dsworkbench with Apache License 2.0 6 votes vote down vote up
/** Creates new form WelcomePanel */
public WelcomePanel() {
    initComponents();
    setOpaque(true);
    welcomeTooltipMap.put(jxHelpLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>Integrierte Hilfe</h2> DS Workbench bietet eine umfangreiche Hilfe, die du im Programm jederzeit &uuml;ber <strong>F1</strong> aufrufen kannst. Dabei wird versucht, das passende Hilfethema f&uuml;r die Ansicht, in der du dich gerade befindest, auszuw&auml;hlen. Es schadet aber auch nicht, einfach mal so in der Hilfe zu st&ouml;bern um neue Funktionen zu entdecken. Einsteiger sollten in jedem Fall die ersten drei Kapitel der Wichtigen Grundlagen gelesen haben.</html>");
    welcomeTooltipMap.put(jxCommunityLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>Die DS Workbench Community</h2> Nat&uuml;rlich gibt es neben dir noch eine Vielzahl anderer Spieler, die DS Workbench regelm&auml;&szlig;ig und intensiv benutzen. Einen perfekten Anlaufpunkt f&uuml;r alle Benutzer bietet das DS Workbench Forum, wo man immer jemanden trifft mit dem man Erfahrungen austauschen und wo man Fragen stellen kann.</html>");
    welcomeTooltipMap.put(jxIdeaLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>Verbesserungen und Ideen </h2> Gibt es irgendwas wo du meinst, dass es in DS Workbench fehlt und was anderen Benutzern auch helfen k&ouml;nnte? Hast du eine Idee, wie man DS Workbench verbessern oder die Handhabung vereinfachen k&ouml;nnte? Dann bietet dieser Bereich im DS Workbench Forum die perfekte Anlaufstelle f&uuml;r dich. Trau dich und hilf mit, DS Workbench  zu verbessern. </html>");
    welcomeTooltipMap.put(jxFacebookLabel, "<html> <h2 style='color:#953333; font-weight: bold;'>DS Workbench @ Facebook</h2> Nat&uuml;rlich geh&ouml;rt es heutzutage fast zum guten Ton, bei Facebook in irgendeiner Art und Weise vertreten zu sein. Auch DS Workbench hat eine eigene Facebook Seite, mit deren Hilfe ihr euch jederzeit &uuml;ber aktuelle News oder Geschehnisse im Zusammenhang mit DS Workbench informieren k&ouml;nnt.</html>");
    welcomeTooltipMap.put(jContentLabel, "<html> <h2 style='color:#953333'>Willkommen bei DS Workbench</h2> Wenn du diese Seite siehst, dann hast du DS Workbench erfolgreich installiert und die ersten Schritte ebenso erfolgreich gemeistert. Eigentlich steht nun einer unbeschwerten Angriffsplanung und -durchf&uuml;hrung nichts mehr im Wege. Erlaube mir trotzdem kurz auf einige Dinge hinzuweisen, die dir m&ouml;glicherweise beim <b>Umgang mit DS Workbench helfen</b> oder aber dir die M&ouml;glichkeit geben, einen wichtigen Teil zur <b>Weiterentwicklung und stetigen Verbesserung</b> dieses Programms beizutragen. Fahre einfach mit der Maus &uuml;ber eins der vier Symbole in den Ecken, um hilfreiche und interessante Informationen rund um DS Workbench zu erfahren. Klicke auf ein Symbol, um direkt zum entsprechenden Ziel zu gelangen. Die Eintr&auml;ge findest du sp&auml;ter auch im Hauptmen&uuml; unter 'Sonstiges'. <br> <h3 style='color:#953333'> Nun aber viel Spa&szlig; mit DS Workbench.</h3> </html>");
    try {
        back = ImageIO.read(WelcomePanel.class.getResource("/images/c.gif"));
    } catch (Exception ignored) {
    }
    if (back != null) {
        setBackgroundPainter(new MattePainter(new TexturePaint(back, new Rectangle2D.Float(0, 0, 200, 20))));
    }
}
 
Example #17
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an image of what currently is drawn on the canvas.
 * <p/>
 * Throws an {@link ActivitiException} when {@link #close()} is already
 * called.
 */
public InputStream generateImage(String imageType) {
    if (closed) {
        throw new ActivitiException("ProcessDiagramGenerator already closed");
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        // Try to remove white space
        minX = (minX <= 5) ? 5 : minX;
        minY = (minY <= 5) ? 5 : minY;
        BufferedImage imageToSerialize = processDiagram;
        if (minX >= 0 && minY >= 0) {
            imageToSerialize = processDiagram.getSubimage(minX - 5, minY - 5, canvasWidth - minX + 5, canvasHeight - minY + 5);
        }
        ImageIO.write(imageToSerialize, imageType, out);
    } catch (IOException e) {
        throw new ActivitiException("Error while generating process image", e);
    } finally {
        IoUtil.closeSilently(out);
    }
    return new ByteArrayInputStream(out.toByteArray());
}
 
Example #18
Source File: BrowserManager.java    From BHBot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method is meant to be used for development purpose. In some situations you want to "fake" the readScreen result
 * with an hand-crafted image. If this is the case, this method is here to help with it.
 *
 * @param screenFilePath the path to the image to be used to load the screen
 */
@SuppressWarnings("unused")
void loadScreen(String screenFilePath) {
    File screenImgFile = new File(screenFilePath);

    if (screenImgFile.exists()) {
        BufferedImage screenImg = null;
        try {
            screenImg = ImageIO.read(screenImgFile);
        } catch (IOException e) {
            BHBot.logger.error("Error when loading game screen ", e);
        }

        img = screenImg;
    } else {
        BHBot.logger.error("Impossible to load screen file: " + screenImgFile.getAbsolutePath());
    }
}
 
Example #19
Source File: ImageUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
public static final Icon createImageIconFromAssets(String imageName, int maxHeight) {
	File cacheFile = new File(TMP_ASSETS_ICONS_FILE, imageName);
	logger.debug("icon: {}", imageName);
	try {
		if ( !cacheFile.exists() ) {
			downloadImageToFile(cacheFile, ASSETS_ICONS_DIR.concat(imageName));
		}
		FileInputStream fis = new FileInputStream(cacheFile);
		BufferedImage image = ImageIO.read(fis);
		int height = image.getHeight();
		if ( height > maxHeight ) {
			image = GraphicsUtilities.createThumbnail(image, maxHeight);
		}
		ImageIO.write(image, "png", cacheFile);
		ImageIcon icon = new ImageIcon(image);
		return icon;				
	} catch (IOException e) {
		logger.warn("Failed to read: {}", cacheFile.getAbsolutePath());
		logger.error("Exception", e);
		downloadImageToFile(cacheFile, ASSETS_ICONS_DIR.concat(imageName));
	}
	MissingIcon imageIcon = new MissingIcon();
	return imageIcon;
}
 
Example #20
Source File: AWTLoader.java    From MikuMikuStudio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public Object load(AssetInfo info) throws IOException {
    if (ImageIO.getImageWritersBySuffix(info.getKey().getExtension()) != null){
        
        boolean flip = ((TextureKey) info.getKey()).isFlipY();
        InputStream in = null;
        try {
            in = info.openStream();
            Image img = load(in, flip);
            return img;
        } finally {
            if (in != null){
                in.close();
            }
        }
    }
    return null;
}
 
Example #21
Source File: ReadUnsignedIntTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);

    dos.writeInt(1);
    dos.writeInt(0x7fffffff);
    dos.writeInt(0x8fffffff);
    dos.writeInt(0xffffffff);

    dos.close();

    ByteArrayInputStream bais =
        new ByteArrayInputStream(baos.toByteArray());
    ImageInputStream iis = ImageIO.createImageInputStream(bais);
    for (int i=0; i<4; i++) {
        long res = iis.readUnsignedInt();
        if (res <= 0) {
            throw new RuntimeException("Negative number was read: "+
                                       Long.toString(res, 16));
        }
    }
}
 
Example #22
Source File: SliceRequest.java    From dawnsci with Eclipse Public License 1.0 5 votes vote down vote up
private void sendImage(IDataset            data, 
					   HttpServletRequest  request,
		               HttpServletResponse response, 
		               Format              format) throws Exception {
	
	data.squeeze();
	
	if (data.getRank()!=2 && data.getRank()!=1) {
		throw new Exception("The data used to make an image must either be 1D or 2D!"); 
	}
		
	response.setContentType("image/jpeg");
	response.setStatus(HttpServletResponse.SC_OK);

	ImageServiceBean bean = createImageServiceBean();
	bean.setImage(data);
	
	// Override histo if they set it.
	String histo = decode(request.getParameter("histo"));
	if (histo!=null) bean.decode(histo);

	IImageService service = ServiceHolder.getImageService();

	if (service == null) {
		throw new NullPointerException("Image service not set");
	}

	final ImageData    imdata = service.getImageData(bean);
	final BufferedImage image = service.getBufferedImage(imdata);
	
	ImageIO.write(image, format.getImageIOString(), response.getOutputStream());
}
 
Example #23
Source File: Skin.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
public Skin(ImageInputStream inputStream, String model) {
    BufferedImage image;
    try {
        image = ImageIO.read(inputStream);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    this.parseBufferedImage(image);
    this.setSkinId(model);
}
 
Example #24
Source File: IncorrectTextSize.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException {
    for (int  point = 5; point < 11; ++point) {
        Graphics2D g2d = bi.createGraphics();
        g2d.setFont(new Font(Font.DIALOG, Font.PLAIN, point));
        g2d.scale(scale, scale);
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.green);
        g2d.drawString(TEXT, 0, 20);
        int length = g2d.getFontMetrics().stringWidth(TEXT);
        if (length < 0) {
            throw new RuntimeException("Negative length");
        }
        for (int i = (length + 1) * scale; i < width; ++i) {
            for (int j = 0; j < height; ++j) {
                if (bi.getRGB(i, j) != Color.white.getRGB()) {
                    g2d.drawLine(length, 0, length, height);
                    ImageIO.write(bi, "png", new File("image.png"));
                    System.out.println("length = " + length);
                    System.err.println("Wrong color at x=" + i + ",y=" + j);
                    System.err.println("Color is:" + new Color(bi.getRGB(i,
                                                                         j)));
                    throw new RuntimeException("Test failed.");
                }
            }
        }
        g2d.dispose();
    }
}
 
Example #25
Source File: ExeCompiler.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public Image[] loadImages(String path) {
    File f = new File(path);

    if (path.toUpperCase().endsWith(".ICO")) {
        //
        // Try to load with our ico codec...
        //
        try {
            java.awt.Image[] images = net.charabia.util.codec.IcoCodec.loadImages(f);
            if ((images != null) && (images.length > 0)) {
                return images;
            }
        } catch (java.io.IOException exc) {
            exc.printStackTrace();
        }
    }

    //
    // defaults to the standard java loading process
    //
    BufferedImage bufferedImage;
    try {
        bufferedImage = ImageIO.read(f);
        javax.swing.ImageIcon icon = new javax.swing.ImageIcon(bufferedImage, "default icon");
        java.awt.Image[] imgs = new java.awt.Image[1];
        imgs[0] = icon.getImage();
        return imgs;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example #26
Source File: GetReaderWriterInfo.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private static void testGetReaderFileSuffixes() {
    String[] suffixes = ImageIO.getReaderFileSuffixes();
    for (String s : suffixes) {
        Iterator<ImageReader> it = ImageIO.getImageReadersBySuffix(s);
        if (!it.hasNext()) {
            throw new RuntimeException("getReaderFileSuffixes returned " +
                                       "an unknown suffix: " + s);
        }
    }
}
 
Example #27
Source File: ExportUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void export(final File targetFile) {
    final BufferedImage image = UIUtils.createScreenshot(component);
    createExecutor(targetFile.getName()).submit(new Runnable() {
        public void run() {
            try {
                targetFile.toPath();
                ImageIO.write(image, "PNG", targetFile); // NOI18N
            } catch (Throwable t) {
                LOGGER.log(Level.INFO, t.getMessage(), t);
                String msg = t.getLocalizedMessage().replace("<", "&lt;").replace(">", "&gt;"); // NOI18N
                ProfilerDialogs.displayError("<html><b>" + MSG_EXPORT_IMAGE_FAILED + "</b><br><br>" + msg + "</html>"); // NOI18N
            }
        }
    });
}
 
Example #28
Source File: Dm3270Context.java    From xframium-java with GNU General Public License v3.0 5 votes vote down vote up
public void takeSnapShot(OutputStream output)
{
    JavaFxRunnable worker = new JavaFxRunnable()
        {
            public void myWork()
                throws Exception
            {
                Scene scene = console.getConsoleScene();
                
                WritableImage writableImage = 
                    new WritableImage((int)scene.getWidth(), (int)scene.getHeight());
                scene.snapshot(writableImage);
     
                try
                {
                    ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", output);
                }
                catch (IOException ex)
                {
                    log.error( "Snapshot failed with: ", ex );
                }
            }
        };

    Platform.runLater( worker );
    worker.doWait();
}
 
Example #29
Source File: ExportUtils.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Writes the current content to the specified file in PNG format.
 * 
 * @param drawable  the drawable (<code>null</code> not permitted).
 * @param w  the chart width.
 * @param h  the chart height.
 * @param file  the output file (<code>null</code> not permitted).
 * 
 * @throws FileNotFoundException if the file is not found.
 * @throws IOException if there is an I/O problem.
 */
public static void writeAsPNG(Drawable drawable, int w, int h, 
        File file) throws FileNotFoundException, IOException {
    BufferedImage image = new BufferedImage(w, h, 
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    drawable.draw(g2, new Rectangle(w, h));
    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    try {
        ImageIO.write(image, "png", out);
    }
    finally {
        out.close();
    }
}
 
Example #30
Source File: ImagePairTest.java    From hifive-pitalium with Apache License 2.0 5 votes vote down vote up
/**
 * 2枚の画像のdominantOffsetを取得するテスト。
 *
 * @throws Exception
 */
@Test
public void testGetDominantOffset() throws Exception {
	BufferedImage expectedImage = ImageIO.read(getClass().getResource("ImagePairTest_missing_expected.png"));
	BufferedImage targetImage = ImageIO.read(getClass().getResource("ImagePairTest_missing_actual.png"));

	ImagePair imagePair = new ImagePair(expectedImage, targetImage);
	imagePair.compareImagePairAll();

	Offset expected = new Offset(0, 0);
	Offset actual = imagePair.getDominantOffset();

	assertThat(actual.getX(), is(expected.getX()));
	assertThat(actual.getY(), is(expected.getY()));
}