我正在尝试使用文件选择器调整图片大小。看起来一切都是文件,但添加文件夹后我无法打开它。
public void metodAddpath(String fullPath) {
try {
File sourceFile = new File(fullPath);
BufferedImage bufferedimage = ImageIO.read(sourceFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
FileOutputStream fileOutputStream = new FileOutputStream(
sourceFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = is.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
is.close();
fileOutputStream.close();
//scaleImage(bufferedimage, 220, 220);
} catch(Exception e) {
e.printStackTrace();
}
} 当我按下按钮将图像保存到文件夹中后。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Database base = new Database();
metodAddpath(jTextField1.getText());
base.addPictureResource(jTextField1.getText());
}
但是当我尝试将其添加到文件夹中时,出现错误。
最佳答案
我只是想站出来说出来,这些都不是......
try {
File sourceFile = new File(fullPath);
BufferedImage bufferedimage = ImageIO.read(sourceFile);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(bufferedimage, "jpg", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
FileOutputStream fileOutputStream = new FileOutputStream(
sourceFile);
int bufferSize;
byte[] bufffer = new byte[512];
while ((bufferSize = is.read(bufffer)) > 0) {
fileOutputStream.write(bufffer, 0, bufferSize);
}
is.close();
fileOutputStream.close();
//scaleImage(bufferedimage, 220, 220);
} catch(Exception e) {
e.printStackTrace();
}
有道理。
您正在读取图像,将其写入ByteArrayOutputStream
,通过InputStream
进行管道传输,然后使用该输入流通过a将内容写入另一个文件FileOutputStream
...为什么?!
类似...
File sourceFile = new File(fullPath);
try {
BufferedImage bufferedimage = ImageIO.read(sourceFile);
//scaleImage(bufferedimage, 220, 220);
// Beware, this is overwriting the existing file
try (FileOutputStream fileOutputStream = new FileOutputStream(sourceFile)) {
ImageIO.write(bufferedimage, "jpg", fileOutputStream);
}
} catch(Exception e) {
e.printStackTrace();
}
会做同样的工作,更容易阅读并且可能更高效......
我怀疑这会回答你的问题,但它可能会减少一些困惑
关于java - 缩放文件夹中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53548804/