Package chunmap.util.image

Source Code of chunmap.util.image.ImageCache

/**
* Copyright (c) 2009-2011, chunquedong(YangJiandong)
*
* This file is part of ChunMap project
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
*
* History:
*     2010-05-05  Jed Young  Creation
*/
package chunmap.util.image;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;

import javax.imageio.ImageIO;

import chunmap.raster.ChunMapIOException;

public class ImageCache {
  public int cacheSize=200;
  private String path = "D:\\Temp\\chunmapData\\googlemap";
  public String format="png";

    private HashMap<String, Image> hash = new HashMap<String, Image>();
    private LinkedList<String> queue = new LinkedList<String>();

    public ImageCache(){
      this.setBufferPath(path);
    }
    public void save(Image image, String name)
    {
      File file;
    try {
      file = createFile(path , name + "."+format);
      ImageIO.write((RenderedImage)image,format,file);
     
    } catch (IOException e) {
      e.printStackTrace();
      throw new ChunMapIOException();
    }
        cache(image, name);
    }
   
    private File createFile(String path, String name) throws IOException {
    File file = new File(path + File.separator + name);
    if (!file.exists()) {
      file.createNewFile();
    }
    return file;
  }

    private void cache(Image image, String name)
    {
        if (hash.size() >= cacheSize)
        {
            for (int i = 0; i < cacheSize/2; i++)
            {
                String key = queue.removeLast();
                hash.remove(key);
            }
        }
        hash.put(name, image);
        queue.addFirst(name);
    }

    public Image find(String name)
    {
        if (hash.containsKey(name))
        {
            return hash.get(name);
        }
        String imagepath = path + File.separator + name + "."+format;
        File file=new File(imagepath);
        if(!file.exists())return null;
   
        Image image;
    try {
      image = ImageIO.read(file);
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
   
        cache(image, name);
        return image;
    }

    public void setBufferPath(String path)
    {
      File file = new File(path);
      if(!file.exists()){
        file.mkdir();
      }
    this.path = path;
    }
}
TOP

Related Classes of chunmap.util.image.ImageCache

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.