java - 保存图像时将其保存为黑色透明而不是真实图像
问题描述
当保存图像时,它会变成黑色方块而不是选择的图像,我希望能够从我的计算机中保存图像并将其保存在项目的文件夹中,以便在压缩和发送时他们可以查看我上传的图像。
我试过BufferedImage.TYPE_INT_ARGB
了,但我不知道这是否是问题所在。
private void imageToArray(){
int width = originalBI.getWidth();
int height = originalBI.getHeight();
newBI = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
pixels = new int[width][height];
for(int i = 0; i<width;i++){
for(int j = 0;j<height;j++){
pixels[i][j]=originalBI.getRGB(i,j);
}
}
}
private void saveImage(){
int returnValue = saveFileChooser.showSaveDialog(this);
if(returnValue == JFileChooser.APPROVE_OPTION) {
try{
ImageIO.write(newBI, "png",saveFileChooser.getSelectedFile());
lblMessage.setText("Image File Succesfully saved");
}catch(IOException ex){
lblMessage.setText("Failed to save image file");
}
}
else{
lblMessage.setText("No file Choosen");
}
}
解决方案
不需要逐个像素地工作,这会很慢。
private void imageToArray(){
int width = originalBI.getWidth();
int height = originalBI.getHeight();
newBI = new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newBI.createGraphics();
g.drawImage(originalBI, 0, 0, width, height, null);
g.dispose();
}
可以创建一个图形来绘制。
有多种方法,例如在图像的一部分透明时使用背景颜色。
推荐阅读
- qt - 主窗口高度动画时巨大的闪烁
- docker - 如何在 localhost 中查看 docker 镜像
- ios - 在 swift 5 中以编程方式更改比例约束
- ruby-on-rails - 添加唯一索引后rails rspec重复键值违反唯一约束
- postgresql - 列引用在 Postgresql 查询中是不明确的,即使子查询明确命名了该列
- python - 如何使用格式填充空格
- sql - sql:从每个组中删除最旧的n条记录
- javascript - 使用 SignalR 获取角色中的用户列表
- visual-studio-code - VS 代码编辑器.autoIndent
- python-3.x - pd.Series(pred).value_counts() 如何获取数据框中的第一列?