Java Code Examples for javax.imageio.ImageIO

The following examples show how to use javax.imageio.ImageIO. These examples are extracted from open source projects.
Example 1
Project: cxf   File: ImageHelper.java    License: 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 2
Project: xnx3   File: ImageUtil.java    License: 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 3
Project: hottub   File: GifTransparencyTest.java    License: GNU General Public License v2.0 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 4
Project: jdk8u-dev-jdk   File: EncodeSubImageTest.java    License: 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 5
Project: spring-content   File: JpegToPngRenditionProvider.java    License: Apache License 2.0 6 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 6
Project: CodeChickenCore   File: GuiModListScroll.java    License: 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 7
Project: netbeans   File: IconEditor.java    License: 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
Project: jpress   File: ImageUtils.java    License: 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
Project: astor   File: SunJPEGEncoderAdapter.java    License: 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
Project: jenetics   File: EvolvingImagesCmd.java    License: 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
Project: scrimage   File: GifWriter.java    License: 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
Project: MikuMikuStudio   File: AWTLoader.java    License: 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 13
Project: openjdk-jdk8u-backup   File: JpegDataContentHandler.java    License: 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 14
Project: jdk8u_jdk   File: ReadUnsignedIntTest.java    License: 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 15
Project: openjdk-jdk8u-backup   File: MergeStdCommentTest.java    License: 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 16
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java    License: 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 17
Project: pyramid   File: KMeansTest.java    License: 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 18
Project: dsworkbench   File: WelcomePanel.java    License: 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 19
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java    License: 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 20
Project: BHBot   File: BrowserManager.java    License: 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 21
Project: gameserver   File: ImageUtil.java    License: 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 22
Project: openjdk-jdk9   File: DrawRotatedStringUsingRotatedFont.java    License: 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 23
Project: jdk8u_jdk   File: AppContextTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void run() {
//          System.out.println("Thread " + threadName + " in thread group " +
//                             getThreadGroup().getName());

        // Create a new AppContext as though we were an applet
        SunToolkit.createNewAppContext();

        // Get default registry and store reference
        this.registry = IIORegistry.getDefaultInstance();

        for (int i = 0; i < 10; i++) {
//              System.out.println(threadName +
//                                 ": setting cache parameters to " +
//                                 useCache + ", " + cacheDirectory);
            ImageIO.setUseCache(useCache);
            ImageIO.setCacheDirectory(cacheDirectory);

            try {
                sleep(1000L);
            } catch (InterruptedException e) {
            }

//              System.out.println(threadName + ": reading cache parameters");
            boolean newUseCache = ImageIO.getUseCache();
            File newCacheDirectory = ImageIO.getCacheDirectory();
            if (newUseCache != useCache ||
                newCacheDirectory != cacheDirectory) {
//                  System.out.println(threadName + ": got " +
//                                     newUseCache + ", " +
//                                     newCacheDirectory);
//                  System.out.println(threadName + ": crosstalk encountered!");
                gotCrosstalk = true;
            }
        }
    }
 
Example 24
Project: xframium-java   File: Dm3270Context.java    License: 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 25
Project: Hotel-Properties-Management-System   File: HotelPropertiesWindow.java    License: GNU General Public License v2.0 5 votes vote down vote up
private ActionListener addPictureListener() {
    final ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser sec = new JFileChooser();
            FileNameExtensionFilter JpegFilter = new FileNameExtensionFilter("JPG & GIF & PNG Images", "jpg", "gif", "png");
            sec.setFileFilter(JpegFilter);
            sec.setAcceptAllFileFilterUsed(false);
            sec.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int result = sec.showOpenDialog(sec);
            if (result == JFileChooser.APPROVE_OPTION) {
                try {

                    newImage = ImageIO.read(sec.getSelectedFile());

                    final int pictureWidth = 586;
                    final int pictureHeight = 218;

                    BufferedImage hotelPicture = new BufferedImage(pictureWidth, pictureHeight, newImage.getType());
                    Graphics2D g = hotelPicture.createGraphics();
                    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                    g.drawImage(newImage, 0, 0, pictureHeight, pictureHeight, null);
                    g.dispose();

                    pictlabel.setIcon(new ImageIcon(hotelPicture));
                    pictlabel.revalidate();
                    pictlabel.repaint();

                } catch (IOException e1) {
                    JOptionPane.showMessageDialog(modalFrame, "Image cannot be null !",
                            JOptionPane.MESSAGE_PROPERTY, JOptionPane.WARNING_MESSAGE);
                }
            }

        }
    };
    return listener;
}
 
Example 26
Project: davmail   File: ExeCompiler.java    License: 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 27
Project: New-Beginner-Java-Game-Programming-Src   File: ImageLoader.java    License: Creative Commons Zero v1.0 Universal 5 votes vote down vote up
public static BufferedImage loadImage(String path){
	try {
		return ImageIO.read(ImageLoader.class.getResource(path));
	} catch (IOException e) {
		e.printStackTrace();
		System.exit(1);
	}
	return null;
}
 
Example 28
Project: MeetingFilm   File: MatrixToImageWriter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * As {@link #writeToStream(BitMatrix, String, OutputStream)}, but allows customization of the output.
 */
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream, MatrixToImageConfig config) 
    throws IOException {  
  BufferedImage image = toBufferedImage(matrix, config);
  if (!ImageIO.write(image, format, stream)) {
    throw new IOException("Could not write an image of format " + format);
  }
}
 
Example 29
Project: Bytecoder   File: TIFFJPEGDecompressor.java    License: Apache License 2.0 5 votes vote down vote up
public void beginDecoding() {
    // Initialize the JPEG reader if needed.
    if(this.JPEGReader == null) {
        // Get all JPEG readers.
        Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("jpeg");

        if(!iter.hasNext()) {
            throw new IllegalStateException("No JPEG readers found!");
        }

        // Initialize reader to the first one.
        this.JPEGReader = iter.next();

        this.JPEGParam = JPEGReader.getDefaultReadParam();
    }

    // Get the JPEGTables field.
    TIFFImageMetadata tmetadata = (TIFFImageMetadata)metadata;
    TIFFField f =
        tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_JPEG_TABLES);

    if (f != null) {
        this.hasJPEGTables = true;
        this.tables = f.getAsBytes();
    } else {
        this.hasJPEGTables = false;
    }
}
 
Example 30
Project: jdk8u-dev-jdk   File: DrawRotatedString.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void verify(BufferedImage bi) throws IOException {
    for (int i = 0; i < SIZE; ++i) {
        for (int j = 0; j < 99; ++j) {
            //Text should not appear before 100
            if (bi.getRGB(i, j) != Color.RED.getRGB()) {
                ImageIO.write(bi, "png", new File("image.png"));
                throw new RuntimeException("Failed: wrong text location");
            }
        }
    }
}
 
Example 31
Project: openjdk-jdk8u-backup   File: IncorrectDestinationOffset.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void validate(BufferedImage bi, int point2draw,
                             int size2draw)
        throws IOException {
    for (int x = 0; x < SIZE; ++x) {
        for (int y = 0; y < SIZE; ++y) {
            if (isInsideGreenArea(point2draw, size2draw, x, y)) {
                if (bi.getRGB(x, y) != Color.green.getRGB()) {
                    ImageIO.write(bi, "png", new File("image.png"));
                    throw new RuntimeException("Test failed.");
                }
            } else {
                if (isRedArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.red.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
                if (isBlueArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.blue.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
                if (isOrangeArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.orange.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
                if (isMagentaArea(x, y)) {
                    if (bi.getRGB(x, y) != Color.magenta.getRGB()) {
                        ImageIO.write(bi, "png", new File("image.png"));
                        throw new RuntimeException("Test failed.");
                    }
                }
            }
        }
    }
}
 
Example 32
Project: jmonkeyengine   File: AWTLoader.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Image load(InputStream in, boolean flipY) throws IOException{
    ImageIO.setUseCache(false);
    BufferedImage img = ImageIO.read(in);
    if (img == null){
        return null;
    }
    return load(img, flipY);
}
 
Example 33
Project: EnchantmentCracker   File: ImagePanel.java    License: MIT License 5 votes vote down vote up
public ImagePanel(String img) {
    try {
        backgroundImage = new BufferedImage[] { ImageIO.read(EnchCrackerWindow.getFile(img+".png")) };
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }
    setOpaque(false);
    setBackground(new Color(255,255,255,0));
}
 
Example 34
Project: GVGAI_GYM   File: SerializableStateObservation.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] imageToByteArray() throws IOException {
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    File pngfile = new File(CompetitionParameters.SCREENSHOT_FILENAME);
    if (pngfile != null) {
        ImageIO.write(ImageIO.read(pngfile), "png", output);
        imageArray = output.toByteArray();
        if (imageArray == null) {
            System.out.println("SerializableStateObservation: imageToByteArray(): imageArray is null");
        }
    } else {
        System.err.println("SerializableStateObservation: imageToByteArray(): pngfile is null");
    }
    return imageArray;
}
 
Example 35
Project: deeplearning4j   File: BinaryModelServerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public BufferedImage deserialize(byte[] buffer) {
    try {
        BufferedImage img = ImageIO.read(new ByteArrayInputStream(buffer));
        return img;
    } catch (IOException e){
        throw new RuntimeException(e);
    }
}
 
Example 36
Project: dubai   File: CaptchaController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(method = RequestMethod.GET)
public void validateCode(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {

    httpServletResponse.setHeader("Cache-Control", "no-store");
    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setDateHeader("Expires", 0);

    String captchaString = CaptchaUtil.generateString(CaptchaUtil.TYPE_NUM_UPPER, 4, null);
    httpServletRequest.getSession().setAttribute(ShiroConstant.CAPTCHA_SESSION_KEY, captchaString);
    httpServletResponse.setContentType("image/jpeg");
    BufferedImage bim = CaptchaUtil.generateImage(captchaString, 90, 30, 3, true, Color.WHITE, null, null);
    ImageIO.write(bim, "JPEG", httpServletResponse.getOutputStream());
}
 
Example 37
Project: jdk8u-dev-jdk   File: TestLoggingWithMainAppContext.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    System.out.println("Creating loggers.");

    // These loggers will be created in the default user context.
    final Logger foo1 = Logger.getLogger( "foo" );
    final Logger bar1 = Logger.getLogger( "foo.bar" );
    if (bar1.getParent() != foo1) {
        throw new RuntimeException("Parent logger of bar1 "+bar1+" is not "+foo1);
    }
    System.out.println("bar1.getParent() is the same as foo1");

    // Set a security manager
    System.setSecurityManager(new SecurityManager());
    System.out.println("Now running with security manager");

    // Triggers the creation of the main AppContext
    ByteArrayInputStream is = new ByteArrayInputStream(new byte[] { 0, 1 });
    ImageIO.read(is); // triggers calls to system loggers & creation of main AppContext

    // verify that we're still using the default user context
    final Logger bar2 = Logger.getLogger( "foo.bar" );
    if (bar1 != bar2) {
        throw new RuntimeException("bar2 "+bar2+" is not the same as bar1 "+bar1);
    }
    System.out.println("bar2 is the same as bar1");
    if (bar2.getParent() != foo1) {
        throw new RuntimeException("Parent logger of bar2 "+bar2+" is not foo1 "+foo1);
    }
    System.out.println("bar2.getParent() is the same as foo1");
    final Logger foo2 = Logger.getLogger("foo");
    if (foo1 != foo2) {
        throw new RuntimeException("foo2 "+foo2+" is not the same as foo1 "+foo1);
    }
    System.out.println("foo2 is the same as foo1");

    System.out.println("Test passed.");
}
 
Example 38
Project: jfinal-api-scaffold   File: FileUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 判断文件是否是图片*
 * @param imgFile 文件对象
 * @return
 */
public static boolean isImage(File imgFile) {
    try {
        BufferedImage image = ImageIO.read(imgFile);
        return image != null;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example 39
Project: tess4j   File: ImageIOHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * Gets a list of <code>IIOImage</code> objects for an image file.
     *
     * @param inputFile input image file. It can be any of the supported
     * formats, including TIFF, JPEG, GIF, PNG, BMP, JPEG, and PDF if GPL
     * Ghostscript or PDFBox is installed
     * @return a list of <code>IIOImage</code> objects
     * @throws IOException
     */
    public static List<IIOImage> getIIOImageList(File inputFile) throws IOException {
        // convert to TIFF if PDF
        File imageFile = getImageFile(inputFile);

        List<IIOImage> iioImageList = new ArrayList<IIOImage>();
        String imageFormat = getImageFileFormat(imageFile);

        Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imageFormat);
        if (!readers.hasNext()) {
            throw new RuntimeException(JAI_IMAGE_READER_MESSAGE);
        }
        ImageReader reader = readers.next();

        try (ImageInputStream iis = ImageIO.createImageInputStream(imageFile)) {
            reader.setInput(iis);

            int imageTotal = reader.getNumImages(true);

            for (int i = 0; i < imageTotal; i++) {
//                IIOImage oimage = new IIOImage(reader.read(i), null, reader.getImageMetadata(i));
                IIOImage oimage = reader.readAll(i, reader.getDefaultReadParam());
                iioImageList.add(oimage);
            }

            return iioImageList;
        } finally {
            if (reader != null) {
                reader.dispose();
            }

            // delete temporary TIFF image for PDF
            if (imageFile != null && imageFile.exists() && imageFile != inputFile && imageFile.getName().startsWith("multipage") && imageFile.getName().endsWith(TIFF_EXT)) {
                imageFile.delete();
            }
        }
    }
 
Example 40
Project: spring-batch-performance-tuning   File: ImageProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ProcessedImage process(ImageSubmission imageSubmission) throws Exception {
	final String imagePath = path + imageSubmission.getFileName();

	try {
		final BufferedImage originalImage = ImageIO.read(new File(imagePath));
		final BufferedImage resizedImage = Scalr.resize(originalImage, width, height);

		return new ProcessedImage(resizedImage, imageSubmission.getFileName());
	} catch (Exception e) {
		LOG.warn("Failed to convert " + imagePath + ", skipping - sorry submitter! (" + e.getMessage() + ")");

		return null;
	}
}