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. 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 Project: cxf   Source 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
Source Project: xnx3   Source 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
Source Project: hottub   Source 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
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
Source Project: spring-content   Source 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
Source Project: CodeChickenCore   Source 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
Source Project: netbeans   Source 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
Source Project: jpress   Source 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
Source Project: astor   Source 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
Source Project: jenetics   Source 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
Source Project: scrimage   Source 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
Source Project: MikuMikuStudio   Source 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
/**
 * 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
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
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
/**
 * 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
Source Project: pyramid   Source 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
Source Project: dsworkbench   Source 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
/**
 * 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
Source Project: BHBot   Source 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
Source Project: gameserver   Source 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
/**
 * 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
Source Project: jdk8u_jdk   Source 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
Source Project: xframium-java   Source 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
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
Source Project: davmail   Source 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
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
Source Project: MeetingFilm   Source 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
Source Project: Bytecoder   Source 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
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");
            }
        }
    }
}