Processing – PImage – saveImageIO

  • タグ:
  • タグはありません
protected boolean saveImageIO(String path) throws IOException {
    try {
      int outputFormat = (format == ARGB) ?
        BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
      
      // JPEG and BMP images that have an alpha channel set get pretty unhappy.
      // BMP just doesn't write, and JPEG writes it as a CMYK image.
      // http://code.google.com/p/processing/issues/detail?id=415
      String lower = path.toLowerCase();
      if (lower.endsWith("bmp") || lower.endsWith("jpg") || lower.endsWith("jpeg")) {
        outputFormat = BufferedImage.TYPE_INT_RGB;
      }
      
      BufferedImage bimage = new BufferedImage(width, height, outputFormat);
      bimage.setRGB(0, 0, width, height, pixels, 0, width);

      File file = new File(path);
      String extension = path.substring(path.lastIndexOf('.') + 1);

      return ImageIO.write(bimage, extension, file);

    } catch (Exception e) {
      e.printStackTrace();
      throw new IOException("image save failed.");
    }
  }