Images are often needed to be cached to save RAM. This small class offers a method to save Images in temporary files. more >>
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;
import javax.imageio.ImageIO;
public class CacheableImage{
private File tempFile;
public boolean cache(BufferedImage content) throws IOException{
if(null==content) return false;
if(null==tempFile){
Random random = new Random();
int v = random.nextInt(1000000);
String pref="temp_"+Integer.toString(v)+"_"+System.currentTimeMillis();
tempFile = File.createTempFile(pref, ".png");
System.out.println("temporary file created: " +tempFile.getPath());
tempFile.deleteOnExit();
}
ImageIO.write(content, "png", tempFile);
System.out.println("temporary file written: " +tempFile.getPath());
return true;
}
public BufferedImage getImage() throws IOException{
if(null!=tempFile)
return ImageIO.read(tempFile);
return null;
}
public File getTempFile(){
return tempFile;
}
}
import javax.swing.*;
import java.awt.image.*;
import java.awt.*;
import javax.imageio.ImageIO;
public class TestFrame extends JFrame {
public static void main(String[] args){
TestFrame f=new TestFrame();
BufferedImage buf=new BufferedImage(400,300, BufferedImage.TYPE_INT_RGB);
Graphics g=buf.getGraphics();
g.setColor(Color.RED);
g.fillRect(20,20,50,50);
CachableImage c=new CachableImage();
try{
c.cache(buf);
BufferedImage b= ImageIO.read(c.getTempFile());
f.getContentPane().add(new JLabel(new ImageIcon(b)));
}
catch(Exception ex){
}
f.pack();
f.setVisible(true);
}
}