1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
package miniature;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class AfficheurImage extends JPanel
{
private BufferedImage image = null;
private int width, height;
private double imageHeightPosition, imageWidthPostion;
public AfficheurImage (int width, int height, File imagePath)
{
this.width = width; this.height = height;
this.setBackground(Color.white);
try
{
image = ImageIO.read(imagePath);
image = createCompatibleImage(this.image);
image = createThumbnail(this.image, this.width);
//Centrage de l'image
double imageHeight = this.image.getHeight() * (this.width / this.image.getWidth());
imageHeightPosition = (this.height - imageHeight) / 2;
imageWidthPostion = (this.width - this.image.getWidth()) / 2;
}
catch (IOException ex)
{
Logger.getLogger(AfficheurImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(this.image, (int) imageWidthPostion, (int) imageHeightPosition, null);
this.image.flush();
g.dispose();
}
public static BufferedImage createCompatibleImage(BufferedImage image)
{
GraphicsConfiguration gc = GraphicsEnvironment.getLocalGraphicsEnvironment().
getDefaultScreenDevice().getDefaultConfiguration();
if (image.getColorModel().equals(gc.getColorModel()))
{
return image;
}
else
{
BufferedImage compatibleImage = gc.createCompatibleImage(image.getWidth(), image.getHeight(),
image.getTransparency());
Graphics g = compatibleImage.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return compatibleImage;
}
}
public static BufferedImage createThumbnail(BufferedImage image, int requestedThumbSize)
{
float ratio = (float) image.getWidth() / (float) image.getHeight();
int width = image.getWidth();
BufferedImage thumb = image;
BufferedImage temp = null;
do
{
width /= 2;
if (width < requestedThumbSize)
{
width = requestedThumbSize;
}
temp = new BufferedImage(width, (int) (width / ratio), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = temp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(thumb, 0, 0, temp.getWidth(), temp.getHeight(), null);
g2.dispose();
thumb = temp;
} while (width != requestedThumbSize);
temp = null;
return thumb;
}
} |
Partager