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

The following examples show how to use javax.imageio.ImageIO#setUseCache() . 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
public static byte[] generateCaptcha(Player player) {
	final BufferedImage image = new BufferedImage(255 - 10, 40, BufferedImage.TYPE_INT_RGB);
	final Graphics2D gfx = image.createGraphics();
	final String captcha = words.get(DataConversions.random(0, words.size()));
	gfx.setColor(Color.BLACK);
	gfx.fillRect(0, 0, 255, 40);
	int currentX = 10;
	for (int i = 0; i <= captcha.length() - 1; i++) {
		gfx.setColor(colors.get(DataConversions.random(0, colors.size() - 1)));
		gfx.setFont(loadedFonts[DataConversions.random(0, loadedFonts.length - 1)]);
		gfx.drawString(String.valueOf(captcha.charAt(i)), currentX, DataConversions.random(25, 35));
		currentX += gfx.getFontMetrics().charWidth(captcha.charAt(i)) + (DataConversions.random(5, 10));
	}
	player.setSleepword(captcha);
	try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
		ImageIO.setUseCache(false);
		ImageIO.write(image, "PNG", baos);
		return baos.toByteArray();
	} catch (final IOException e) {
		LOGGER.catching(e);
	} finally {
		gfx.dispose();
		image.flush();
	}
	return null;
}
 
Example 2
/**
 * Get a Tile image from the database.
 * 
 * @param x
 * @param y
 * @param z
 * @return
 * @throws Exception
 */
public BufferedImage getTile( int x, int y, int z ) throws Exception {
    try (PreparedStatement statement = connection.prepareStatement(SELECTQUERY)) {
        statement.setInt(1, z);
        statement.setInt(2, x);
        statement.setInt(3, y);
        ResultSet resultSet = statement.executeQuery();
        if (resultSet.next()) {
            byte[] imageBytes = resultSet.getBytes(1);
            boolean orig = ImageIO.getUseCache();
            ImageIO.setUseCache(false);
            InputStream in = new ByteArrayInputStream(imageBytes);
            BufferedImage bufferedImage = ImageIO.read(in);
            ImageIO.setUseCache(orig);
            return bufferedImage;
        }
    }
    return null;
}
 
Example 3
Source Project: phone   File: ShiroKaptchaServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init(ServletConfig conf) throws ServletException
{
	super.init(conf);

	// Switch off disk based caching.
	ImageIO.setUseCache(false);

	Enumeration<?> initParams = conf.getInitParameterNames();
	while (initParams.hasMoreElements())
	{
		String key = (String) initParams.nextElement();
		String value = conf.getInitParameter(key);
		this.props.put(key, value);
	}

	Config config = new Config(this.props);
	this.kaptchaProducer = config.getProducerImpl();
	this.sessionKeyValue = config.getSessionKey();
	this.sessionKeyDateValue = config.getSessionDate();
}
 
Example 4
public static void main(String[] args) {
    ImageIO.setUseCache(false);
    OutputStream os = new ByteArrayOutputStream();
    ImageOutputStream stream = null;
    try {
        stream = ImageIO.createImageOutputStream(os);
    } catch (Exception e) {
        throw new RuntimeException("Got exception " + e);
    }
    if (stream == null) {
        throw new RuntimeException("Got null stream!");
    }
}
 
Example 5
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    OutputType t = (OutputType)env.getModifier(generalDestRoot);
    outputType = t.getType();
}
 
Example 6
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    OutputType t = (OutputType)env.getModifier(generalDestRoot);
    outputType = t.getType();
}
 
Example 7
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    OutputType t = (OutputType)env.getModifier(generalDestRoot);
    outputType = t.getType();
}
 
Example 8
Source Project: birt   File: JavaxImageIOWriter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public void setProperty( String sProperty, Object oValue )
{
	super.setProperty( sProperty, oValue );
	if ( sProperty.equals( IDeviceRenderer.EXPECTED_BOUNDS ) )
	{
		_bo = (Bounds) oValue;
	}
	else if ( sProperty.equals( IDeviceRenderer.CACHED_IMAGE ) )
	{
		_img = (Image) oValue;
	}
	else if ( sProperty.equals( IDeviceRenderer.FILE_IDENTIFIER ) )
	{
		_oOutputIdentifier = oValue;
	}
	else if ( sProperty.equals( IDeviceRenderer.CACHE_ON_DISK ) )
	{
		ImageIO.setUseCache( ( (Boolean) oValue ).booleanValue( ) );
	}
	else if ( sProperty.equals( IDeviceRenderer.AREA_ALT_ENABLED ) )
	{
		_bAltEnabled = ( (Boolean) oValue ).booleanValue( );
	}
	else if (sProperty.equals( "output.format" )) //$NON-NLS-1$
	{
		outputFormat = (String)oValue;
	}
}
 
Example 9
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    InputType t = (InputType)env.getModifier(generalSourceRoot);
    inputType = t.getType();
}
 
Example 10
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    InputType t = (InputType)env.getModifier(generalSourceRoot);
    inputType = t.getType();
}
 
Example 11
/**
 * Checks if the input file is a PNG using ICC Gray color model
 * If that's the case, converts to RGB and returns the file path
 */
private static Optional<SeekableSource> convertICCGrayPngIf(SeekableSource source) throws IOException, TaskIOException {
    try {
        if (FileType.PNG.equals(getFileType(source))) {
            try (ImageInputStream iis = ImageIO.createImageInputStream(source.asNewInputStream())) {
                ImageReader reader = ImageIO.getImageReadersByFormatName("png").next();
                boolean isICCGray = false;
                try {
                    ImageIO.setUseCache(false);
                    reader.setInput(iis);
                    for (Iterator<ImageTypeSpecifier> it = reader.getImageTypes(0); it.hasNext(); ) {
                        ImageTypeSpecifier typeSpecifier = it.next();
                        ColorSpace colorSpace = typeSpecifier.getColorModel().getColorSpace();
                        if (colorSpace instanceof ICC_ColorSpace && ((ICC_ColorSpace) colorSpace).getProfile() instanceof ICC_ProfileGray) {
                            isICCGray = true;
                            break;
                        }
                    }

                    if (isICCGray) {
                        LOG.debug("Detected a Gray PNG image, will convert to RGB and save to a new file");
                        // convert to rgb
                        BufferedImage original = reader.read(0);
                        BufferedImage rgb = toARGB(original);
                        File tmpFile = IOUtils.createTemporaryBuffer();
                        ImageIO.write(rgb, "png", tmpFile);
                        return Optional.of(SeekableSources.seekableSourceFrom(tmpFile));
                    }
                } finally {
                    reader.dispose();
                }
            }
        }
    } catch (IIOException e) {
        LOG.debug("Failed convertICCGrayPngIf()", e);
    }

    return Optional.empty();
}
 
Example 12
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    InputType t = (InputType)env.getModifier(generalSourceRoot);
    inputType = t.getType();
}
 
Example 13
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    InputType t = (InputType)env.getModifier(generalSourceRoot);
    inputType = t.getType();
}
 
Example 14
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    InputType t = (InputType)env.getModifier(generalSourceRoot);
    inputType = t.getType();
}
 
Example 15
Source Project: gcs   File: JPEGFactory.java    License: Mozilla Public License 2.0 5 votes vote down vote up
private static Raster readJPEGRaster(InputStream stream) throws IOException
{
    // find suitable image reader
    Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName("JPEG");
    ImageReader reader = null;
    while (readers.hasNext())
    {
        reader = readers.next();
        if (reader.canReadRaster())
        {
            break;
        }
    }

    if (reader == null)
    {
        throw new MissingImageReaderException(
                "Cannot read JPEG image: a suitable JAI I/O image filter is not installed");
    }

    ImageInputStream iis = null;
    try
    {
        iis = ImageIO.createImageInputStream(stream);
        reader.setInput(iis);
        ImageIO.setUseCache(false);
        return reader.readRaster(0, null);
    }
    finally
    {
        if (iis != null)
        {
            iis.close();
        }
        reader.dispose();
    }
}
 
Example 16
Source Project: hottub   File: InputTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
Context(TestEnvironment env, Result result) {
    size = env.getIntValue(sizeList);
    if (hasImageIO) {
        if (env.getModifier(useCacheTog) != null) {
            ImageIO.setUseCache(env.isEnabled(useCacheTog));
        }
    }

    InputType t = (InputType)env.getModifier(generalSourceRoot);
    inputType = t.getType();
}
 
Example 17
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 18
public static void main(String[] args) throws IOException {
    ImageIO.setUseCache(true);

    // Create a FileImageOutputStream from a FileOutputStream
    File temp1 = File.createTempFile("imageio", ".tmp");
    temp1.deleteOnExit();
    ImageOutputStream fios = ImageIO.createImageOutputStream(temp1);

    // Create a FileCacheImageOutputStream from a BufferedOutputStream
    File temp2 = File.createTempFile("imageio", ".tmp");
    temp2.deleteOnExit();
    FileOutputStream fos2 = new FileOutputStream(temp2);
    BufferedOutputStream bos = new BufferedOutputStream(fos2);
    ImageOutputStream fcios1 = ImageIO.createImageOutputStream(bos);

    // Create a FileCacheImageOutputStream from a ByteArrayOutputStream
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageOutputStream fcios2 = ImageIO.createImageOutputStream(baos);

    BufferedImage bi =
        new BufferedImage(10, 10, BufferedImage.TYPE_3BYTE_BGR);

    ImageIO.write(bi, "jpg", fios); // No bug, check it anyway
    ImageIO.write(bi, "png", fcios1); // Bug 4414990
    ImageIO.write(bi, "jpg", fcios2); // Bug 4415041

    // It should not be necessary to flush any of the streams
    // If flushing does make a difference, it indicates a bug
    // in the writer or the stream implementation

    // Get length of temp1 before and after flushing
    long file1NoFlushLength = temp1.length();
    fios.flush();
    long file1FlushLength = temp1.length();

    // Get length of temp2 before and after flushing
    long file2NoFlushLength = temp2.length();
    fcios1.flush();
    bos.flush();
    long file2FlushLength = temp2.length();

    byte[] b0 = baos.toByteArray();
    int cacheNoFlushLength = b0.length;
    fcios2.flush();
    byte[] b1 = baos.toByteArray();
    int cacheFlushLength = b1.length;

    if (file1NoFlushLength != file1FlushLength) {
        // throw new RuntimeException
        System.out.println
            ("FileImageOutputStream not flushed!");
    }

    if (file2NoFlushLength != file2FlushLength) {
        // throw new RuntimeException
        System.out.println
         ("FileCacheImageOutputStream/BufferedOutputStream not flushed!");
    }

    if (cacheNoFlushLength != cacheFlushLength) {
        // throw new RuntimeException
        System.out.println
        ("FileCacheImageOutputStream/ByteArrayOutputStream not flushed!");
    }
}
 
Example 19
@BeforeClass
public static void disableCaching() {
    // Disable disk-caching as it slows down fuzzing
    // and makes image reads non-idempotent
    ImageIO.setUseCache(false);
}
 
Example 20
Source Project: QVisual   File: HttpUtils.java    License: Apache License 2.0 3 votes vote down vote up
private static byte[] getImageBytes(BufferedImage image) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    ImageIO.setUseCache(false);
    ImageIO.write(image, "png", baos);

    byte[] imageBytes = baos.toByteArray();

    baos.flush();

    return imageBytes;
}