我有以下代码:
private synchronized void produceSignatureImage(java.awt.event.ActionEvent evt, final String envStrFileName) {
final String es = envStrFileName;
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics().drawImage(img, 0, 0, TrusteeSignature.this);
String filename = sdf.format(new Timestamp(System.currentTimeMillis())) + ".jpg";
File outputfile = new File(IMAGE_FILE_PATH + filename);
String fullPath = outputfile.getAbsolutePath();
if (isNotesLocal()) {
NotesThread.sinitThread();
}
s = openSession();
s.setEnvironmentVar(envStrFileName, fullPath);
ImageIO.write(bufferedImage, "jpg", outputfile);
Button b = (Button) evt.getSource();
b.setEnabled(false);
clear();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (s != null) {
TrusteeSignature.this.closeSession(s);
}
} catch (NotesException e) {
e.printStackTrace();
}
if (isNotesLocal()) {
NotesThread.stermThread();
}
}
}
});
这很好,但是我想将图像尺寸从固定的500x250减小到200x150,减少60%。
我不需要我们要写入文件系统的原始大小的图像,并且很乐意在写入文件之前减小文件的大小。我在此站点的其他地方找到了以下代码。
/**
* we want the x and o to be resized when the JFrame is resized
*
* @param originalImage an x or an o. Use cross or oh fields.
*
* @param biggerWidth
* @param biggerHeight
*/
private Image resizeToBig(Image originalImage, int biggerWidth, int biggerHeight) {
int type = BufferedImage.TYPE_INT_ARGB;
BufferedImage resizedImage = new BufferedImage(biggerWidth, biggerHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.Src);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(originalImage, 0, 0, biggerWidth, biggerHeight, this);
g.dispose();
return resizedImage;
}
我看到图像正在变大。我假设将60%的调整大小数字设置为变量后,也可以通过以下两行代码来减少图像的大小:
BufferedImage resizedImage = new BufferedImage(biggerWidth, biggerHeight, type);
Graphics2D g = resizedImage.createGraphics();
我不确定的是:因为我只想将40%大小的图像写入OS,所以在将JPG文件写入OS之前,我应该在代码的哪个位置进行大小调整?
是的,我是Java新手!
答案 0 :(得分:0)
在您的try
块的开头尝试以下操作:
Image resizedImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics().drawImage(resizedImage, 0, 0, TrusteeSignature.this);
...其中newWidth
和newHeight
等于您希望的调整尺寸,例如200
和150
。
文档:https://docs.oracle.com/javase/8/docs/api/java/awt/Image.html#getScaledInstance-int-int-int-