/** * Method will save the JComponent as an image. The formats are PNG, and * TIFF. * * @param filename * name of the file to store the image into * @param type * of the image to be stored. Can be one of {@value #PNG} for PNG * or {@value #TIFF} for TIFF * @param component * to draw the image on */ public void saveJComponent(String filename, int type, JComponent component) { Dimension size = component.getSize(); BufferedImage image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_BYTE_INDEXED); Graphics2D grp = image.createGraphics(); component.paint(grp); if (type == PNG) { filename += PNG_EXTENSION; this.savePNGWithBatik(filename, image); } else if (type == TIFF) { filename = filename + TIFF_EXTENSION; this.saveTIFFWithBatik(filename, image); } }
SaveGraphicsService save = new SaveGraphicsService(); String ext = filename.substring(filename.length() - 4); String name = filename.substring(0, filename.length() - 4); if (ext.equals(SaveGraphicsService.PNG_EXTENSION)) { save.saveJComponent(name, SaveGraphicsService.PNG, comp); } else if (ext.equals(SaveGraphicsService.TIFF_EXTENSION)) { save.saveJComponent(name, SaveGraphicsService.TIFF, comp); } else { save.saveJComponent(filename, SaveGraphicsService.PNG, comp);
/** * Use Batik to save a PNG of the graph * * @param filename * name of the file to store the image into * @param image * to be stored */ public void savePNGWithBatik(String filename, BufferedImage image) { File outfile = new File(filename); OutputStream fos = createFile(outfile); if (fos == null) { return; } PNGEncodeParam param = PNGEncodeParam.getDefaultEncodeParam(image); PNGImageEncoder encoder = new PNGImageEncoder(fos, param); try { encoder.encode(image); } catch (IOException e) { JMeterUtils.reportErrorToUser("PNGImageEncoder reported: "+e.getMessage(), "Problem creating image file"); } finally { JOrphanUtils.closeQuietly(fos); } }
/** * Use Batik to save a TIFF file of the graph * * @param filename * name of the file to store the image into * @param image * to be stored */ public void saveTIFFWithBatik(String filename, BufferedImage image) { File outfile = new File(filename); OutputStream fos = createFile(outfile); if (fos == null) { return; } TIFFEncodeParam param = new TIFFEncodeParam(); TIFFImageEncoder encoder = new TIFFImageEncoder(fos, param); try { encoder.encode(image); } catch (IOException e) { JMeterUtils.reportErrorToUser("TIFFImageEncoder reported: "+e.getMessage(), "Problem creating image file"); } catch (Error e) { // NOSONAR TIFFImageEncoder uses Error to report runtime problems JMeterUtils.reportErrorToUser("TIFFImageEncoder reported: "+e.getMessage(), "Problem creating image file"); if (e.getClass() != Error.class){// NOSONAR rethrow other errors throw e; } } finally { JOrphanUtils.closeQuietly(fos); } }