Java tutorial
/* * Copyright (c) 2008-2016 * LANIT * All rights reserved. * * This product and related documentation are protected by copyright and * distributed under licenses restricting its use, copying, distribution, and * decompilation. No part of this product or related documentation may be * reproduced in any form by any means without prior written authorization of * LANIT and its licensors, if any. * * $Id$ */ package com.inbook.resource; import javafx.embed.swing.SwingFXUtils; import javafx.scene.image.Image; import org.apache.commons.io.IOUtils; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; public class PngSprite implements Sprite { private static final String SPRITE_DESCRIPTOR_EXT = ".descriptor"; private static final String SPRITE_SMALL_IMAGE_EXT = "_small.png"; private static final String SPRITE_MEDIUM_IMAGE_EXT = "_medium.png"; private static final String SPRITE_LARGE_IMAGE_EXT = "_large.png"; private static final int SCALE_SMALL_WIDTH = 16, SCALE_SMALL_HEIGHT = 16; private static final int SCALE_MEDIUM_WIDTH = 32, SCALE_MEDIUM_HEIGHT = 32; private static final int SCALE_LARGE_WIDTH = 64, SCALE_LARGE_HEIGHT = 64; private final String name; private final String path; private Map<String, Integer> positions; private BufferedImage smallImage; private BufferedImage mediumImage; private BufferedImage largeImage; public PngSprite(String path, String name) { this.path = path; this.name = name; this.positions = new HashMap<>(); loadImages(); loadParts(); } private void loadImages() { try { smallImage = ImageIO.read(getStream(SPRITE_SMALL_IMAGE_EXT)); mediumImage = ImageIO.read(getStream(SPRITE_MEDIUM_IMAGE_EXT)); largeImage = ImageIO.read(getStream(SPRITE_LARGE_IMAGE_EXT)); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") private void loadParts() { try (InputStream io = getStream(SPRITE_DESCRIPTOR_EXT)) { List<String> list = IOUtils.readLines(io); for (int i = 0; i < list.size(); i++) { String iconName = list.get(i); positions.put(iconName, i); } } catch (IOException ex) { ex.printStackTrace(); } } private InputStream getStream(String ext) { return getClass().getClassLoader().getResourceAsStream(path + name + ext); } public Image getSmallIcon(String iconName) { return getIcon(smallImage, SCALE_SMALL_WIDTH, SCALE_SMALL_HEIGHT, iconName); } @Override public Image getMediumIcon(String iconName) { return getIcon(mediumImage, SCALE_MEDIUM_WIDTH, SCALE_MEDIUM_HEIGHT, iconName); } @Override public Image getLargeIcon(String iconName) { return getIcon(largeImage, SCALE_LARGE_WIDTH, SCALE_LARGE_HEIGHT, iconName); } public Image getIcon(BufferedImage source, int width, int height, String iconName) { int position = positions.get(iconName); BufferedImage subimage = source.getSubimage(0, position * height, width, height); return SwingFXUtils.toFXImage(subimage, null); } }