File heduiFile = ExportImage.saveCompoentImage(fileName, poker480JPanel1.getjPanel1(), poker480JPanel1);
OutputStream out = new FileOutputStream(new File("C:\\a.jpg"));
out.write(heduiFile);
out.close();
我想将heduiFile保存为JPG格式。但我仍然无法得到图像?
答案 0 :(得分:0)
我这样做的一种方法是使用这个小的Java方法(下面),它在提供的Swing组件中获取图像,并将其保存到本地文件系统中提供的所需路径和文件名。图像以提供的文件名末尾的扩展名指定的格式保存。如果所需文件名为MyImage.jpg
,则该文件将另存为 JPG 文件。如果文件名为MyImage.png
,则图片会另存为包含Alpha通道的 PNG 文件。该方法支持以下图像格式: GIF , PNG , JPEG , JPG , BMP 和 WBMP :
/**
* Saves the image contained within a Swing component to the local file system. If
* the image file already exists within the supplied path then that file is overwritten.<br>
*
* @param component (JComponent) The Swing Component to get the Image Icon from (ie: JLabel, etc).<br>
*
* @param saveToFilePath (String) The full path and file name of where to save the image file.
* The file name must contain one of the following file name image extensions: .gif, .jpeg,
* .jpg, .bmp, .wbmp, .png. If the file name provided does not contain a file name extension
* then .png is used by default.<br>
*
* @throws IOException
*/
public void saveComponentImage(JComponent component, String saveToFilePath) throws IOException {
String imageType;
String ext = saveToFilePath.substring(saveToFilePath.lastIndexOf(".")).toLowerCase();
String allowableExtentions = ".gif .jpg .jpeg .png .bmp .wbmp";
imageType = allowableExtentions.contains(ext) ? ext.substring(1) : "png";
int rgbType = imageType.equals("png") ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(), rgbType);
Graphics2D g2d = img.createGraphics();
component.printAll(g2d);
g2d.dispose();
File outputfile = new File(saveToFilePath);
ImageIO.write(img, imageType, outputfile);
}
这可能就是你如何使用这种方法:
try { saveComponentImage(jLabel1, "C:\\Pictures\\Some_Image.jpg"); }
catch (IOException ex) { ex.printStackTrace(); }