//package de.illu.zoomviewer;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.ref.SoftReference;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.imageio.ImageIO;
public class ImagePointer implements Runnable
{
public static final BufferedImage LOADING;
static {
LOADING = new BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB);
Graphics g = LOADING.getGraphics();
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0, 0, 400, 300);
g.setColor(Color.BLACK);
g.setFont(new Font("Serif", Font.BOLD, 50));
FontMetrics fm = g.getFontMetrics();
String str = "Loading...";
g.drawString(str, (400 - fm.stringWidth(str)) / 2, 150);
g.dispose();
}
private SoftReference<BufferedImage> image = null;
private String source = null;
private AtomicBoolean threadRuns = new AtomicBoolean(false);
private Thread loadThread;
public BufferedImage getImage()
{
if (image == null || image.get() == null) {
if (threadRuns.compareAndSet(false, true)) {
(loadThread = new Thread(this)).start();
}
return LOADING;
} else {
return image.get();
}
}
public void joinThread() throws IOException
{
if (!threadRuns.get())
return;
try {
loadThread.join(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while loading Image");
}
}
public void run()
{
if (source != null) {
try {
InputStream is = ImagePointer.streamFor(source);
BufferedImage img = ImageIO.read(is);
image = new SoftReference<BufferedImage>(img);
img = null;
is.close();
} catch (IOException e) {
// discard
}
}
threadRuns.set(false);
}
static InputStream streamFor(String source) throws IOException
{
if (source.startsWith("zip:")) {
int i = source.indexOf('|');
File file = new File(source.substring(4, i));
ZipFile zipFile = new ZipFile(file);
ZipEntry entry = zipFile.getEntry(source.substring(i + 1));
InputStream is = zipFile.getInputStream(entry);
return is;
} else {
return new FileInputStream(source);
}
}
public String getSource()
{
return source;
}
public void setSource(String source)
{
this.source = source;
this.image = null;
}
}