簡體   English   中英

來自BufferedImage的新FileDataSource?

[英]new FileDataSource from a BufferedImage?

您可以執行類似的操作來獲取緩沖的圖像作為文件位置嗎?

DataSource source =  new FileDataSource(ImageIO.write(image, "png", file));

我正在嘗試使用Java Mail API將緩沖的圖像作為附件發送,而不必先保存文件?

TIA

構建自己的DataSource類,並從包裝圖像字節的ByteArrayInputStream中獲取輸入流。

就像是 :

public class ImageDataSource implements DataSource {

private Image image = null;
private String imageName = "";

public ImageDataSource( Image image, String imageName ) {
    this.image = image;
    this.imageName = imageName;
}//cons

public InputStream getInputStream() {
  return new ByteArrayInputStream( image.getBytes() );
}//met

public OutputStream getOutputStream() {
  throw new IOException();
}//met

public String getName() {
  return imageName;
}//met

public String getMimeType() {
  return "image/png";
}//met

private byte [] getImgBytes(Image image) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        ImageIO.write(getBufferedImage(image), "png", baos);
    } catch (IOException ex) {
        //handle it here.... not implemented yet...
    }
    return baos.toByteArray();
}//met

}//class

或多或少,我沒有IDE :)

我通過做一些相當la腳的編程工作來解決了這個問題,但是它起作用了:

File file = new File("temp.png");
ImageIO.write(originalImage, "png", file);
DataSource source =  new FileDataSource(file);  

然后,當一切完成后,我只是:

file.delete();

沒有,因為ImageIO.write返回一個boolean ,所以不會編譯, FileDataSource期望在其構造函數中有一個文件/文件名

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM