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 101 102 103 104 105
|
/**
* Type de compression BMP
*/
public final static String IMAGE_TYPE_BMP = "BMP";
/**
* Type de compression WBMP
*/
public final static String IMAGE_TYPE_WBMP = "WBMP";
/**
* Type de compression JPEG
*/
public final static String IMAGE_TYPE_JPEG = "JPEG";
/**
* Type de compression PNG
*/
public final static String IMAGE_TYPE_PNG = "PNG";
public static String cvtImage(File fichierSource, File fichierDestination, String compressionType)
{
// buffer
BufferedImage buf = null;
BufferedImage bufFinal = null;
// récuperation de l'image dans le buffer
try {
buf = ImageIO.read(fichierSource);
}
catch (IOException ex)
{
ex.printStackTrace();
return "non ok";
}
//calcul de l'echelle
int width=buf.getWidth();
int height=buf.getHeight();
int widthMsq=130;
int heightMsq=170;
double echelle=0;
double echelleW=(double) widthMsq / width;
double echelleH=(double) heightMsq / height;
if(echelleW<echelleH) echelle=echelleW; else echelle=echelleH;
echelle=(Math.round(echelle*Math.pow(10,2)) )/ (Math.pow(10,2));
//calcul coordonee pour centrer
int centerX=(int)(widthMsq - (width* echelle)) /2 ;
int centerY=(int) (heightMsq - (height* echelle)) /2 ;
//mise à l'echelle
//buf=scale(buf,echelle);
// Cr�tion du buffer final widthMsq, heightMsq buf.getWidth(), buf.getHeight()
bufFinal = new BufferedImage(widthMsq,heightMsq,buf.getType());//.TYPE_INT_RGB); // masque
// Redimensionnement de l'image si volont�
Graphics2D g = (Graphics2D) bufFinal.getGraphics();
//fond blanc
g.setColor(Color.white);
g.fillRect(0, 0, bufFinal.getWidth(), bufFinal.getHeight());
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(buf, centerX,centerY, (int) (buf.getWidth()* echelle), (int)(buf.getHeight()*echelle), null);
g.dispose();
// Ecriture du fichier destination
try {
ImageIO.write(bufFinal, compressionType,fichierDestination);
}
catch (IOException e)
{
e.printStackTrace();
return "non ok";
}
return fichierDestination.toString();
}
public static void main (String [] args)
{
String resultat="";
//File repertoire=new File(strRepertoire);
//File[] listFile = repertoire.listFiles();
//if(listFile !=null)
// for ( int i = 0; i < listFile.length; i++)
// {
File fichierSource = new File("/tmp/27120.jpg");
File fichierDestination = new File("/tmp/27120-redim.jpg");
if( fichierSource.toString().substring(fichierSource.toString().length()-3,fichierSource.toString().length()).equals("jpg"))
{ resultat=cvtImage(fichierSource, fichierDestination,IMAGE_TYPE_JPEG); }
// }
} |
Partager