|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Junior Member
Iscritto dal: Jul 2012
Messaggi: 12
|
[JAVA] ridimensionare immagine
Ciao Ragazzi,
conoscete una guida su come gestire le immagini in java? Ho la necessità di caricare da un file l'immagine e ridimensionarla e salvare su un nuovo file. Ho provato vari codici che ho trovato ma ottengo sempre un file di 0 byte. Grazie Questo è l'ultimo metodo che ho provato. file è una variabile di classe e getExtension è un metodo che restituisce l'estensione. L'uscita delle dimensioni è corretta. Codice:
public void resizeImg(String savePath, int percent ) {
if (percent == 100)
return;
try {
File fileName = new File(file.getAbsolutePath());
BufferedImage img = ImageIO.read(fileName);
int w = img.getWidth();
int h = img.getHeight();
int type = img.getType();
System.out.println("Dimensioni Originali:" + w +" x " + h);
int targetW = w * percent / 100;
int targetH = h * percent / 100;
BufferedImage ret = (BufferedImage) img;
do {
if (w<targetW) {
w = w * 2;
h = h * 2;
if (w>targetW) {
w = targetW;
h = targetH;
}
}
if (w> targetW) {
w = w/=2;
h = h/=2;
if (w<targetW) {
w = targetW;
h= targetH;
}
}
BufferedImage tmp = new BufferedImage(w, h, type);
Graphics2D g2 = tmp.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(ret, 0, 0, w, h, null);
g2.dispose();
ret = tmp;
} while (w != targetW || h != targetH);
System.out.println("Dimensioni Modificate:" + w +" x " + h);
File resizeFile = new File(savePath);
FileOutputStream fos;
fos = new FileOutputStream(resizeFile);
ImageIO.write(ret, getExtension(), fos);
fos.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Impossible to resize " + file.getName() + "!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
Ultima modifica di forza_sugar : 18-08-2012 alle 16:26. Motivo: aggiunto codice |
|
|
|
|
|
#2 |
|
Junior Member
Iscritto dal: Jul 2012
Messaggi: 12
|
risolto
era sbagliato il metodo getExtension... basta sostituirlo con "jpg"
ciaoo |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 07:41.


















