Use ImageIO functions from Java 1.4 and later to handle image save. Various formats are supported, typically jpeg, png, bmp, and wbmp. To get a list of the supported formats for writing, use: println(javax.imageio.ImageIO.getReaderFormatNames())
(String path)
| 3211 | * <TT>println(javax.imageio.ImageIO.getReaderFormatNames())</TT> |
| 3212 | */ |
| 3213 | protected boolean saveImageIO(String path) throws IOException { |
| 3214 | try { |
| 3215 | int outputFormat = (format == ARGB) ? |
| 3216 | BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB; |
| 3217 | |
| 3218 | String extension = |
| 3219 | path.substring(path.lastIndexOf('.') + 1).toLowerCase(); |
| 3220 | |
| 3221 | // JPEG and BMP images that have an alpha channel set get pretty unhappy. |
| 3222 | // BMP just doesn't write, and JPEG writes it as a CMYK image. |
| 3223 | // http://code.google.com/p/processing/issues/detail?id=415 |
| 3224 | if (extension.equals("bmp") || extension.equals("jpg") || extension.equals("jpeg")) { |
| 3225 | outputFormat = BufferedImage.TYPE_INT_RGB; |
| 3226 | } |
| 3227 | |
| 3228 | BufferedImage bimage = new BufferedImage(pixelWidth, pixelHeight, outputFormat); |
| 3229 | bimage.setRGB(0, 0, pixelWidth, pixelHeight, pixels, 0, pixelWidth); |
| 3230 | |
| 3231 | File file = new File(path); |
| 3232 | |
| 3233 | ImageWriter writer = null; |
| 3234 | ImageWriteParam param = null; |
| 3235 | IIOMetadata metadata = null; |
| 3236 | |
| 3237 | if (extension.equals("jpg") || extension.equals("jpeg")) { |
| 3238 | if ((writer = imageioWriter("jpeg")) != null) { |
| 3239 | // Set JPEG quality to 90% with baseline optimization. Setting this |
| 3240 | // to 1 was a huge jump (about triple the size), so this seems good. |
| 3241 | // Oddly, a smaller file size than Photoshop at 90%, but I suppose |
| 3242 | // it's a completely different algorithm. |
| 3243 | param = writer.getDefaultWriteParam(); |
| 3244 | param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); |
| 3245 | param.setCompressionQuality(0.9f); |
| 3246 | } |
| 3247 | } |
| 3248 | |
| 3249 | if (extension.equals("png")) { |
| 3250 | if ((writer = imageioWriter("png")) != null) { |
| 3251 | param = writer.getDefaultWriteParam(); |
| 3252 | if (false) { |
| 3253 | metadata = imageioDPI(writer, param, 100); |
| 3254 | } |
| 3255 | } |
| 3256 | } |
| 3257 | |
| 3258 | if (writer != null) { |
| 3259 | BufferedOutputStream output = |
| 3260 | new BufferedOutputStream(PApplet.createOutput(file)); |
| 3261 | writer.setOutput(ImageIO.createImageOutputStream(output)); |
| 3262 | // writer.write(null, new IIOImage(bimage, null, null), param); |
| 3263 | writer.write(metadata, new IIOImage(bimage, null, metadata), param); |
| 3264 | writer.dispose(); |
| 3265 | |
| 3266 | output.flush(); |
| 3267 | output.close(); |
| 3268 | return true; |
| 3269 | } |
| 3270 | // If iter.hasNext() somehow fails up top, it falls through to here |
no test coverage detected