List of usage examples for java.awt.image BufferedImage toString
public String toString()
From source file:edu.stanford.epad.epadws.handlers.dicom.DSOUtil.java
public static void writeDSOMaskPNGs(File dsoFile, String username) throws Exception { log.info("Start generating DSO PNGs: " + dsoFile.getName()); String seriesUID = ""; File tmpDSO = File.createTempFile("DSO_" + dsoFile.getName(), ".dcm"); try {//from www. ja va2 s .c o m EPADFileUtils.copyFile(dsoFile, tmpDSO); EpadDatabaseOperations databaseOperations = EpadDatabase.getInstance().getEPADDatabaseOperations(); EpadProjectOperations projectOperations = DefaultEpadProjectOperations.getInstance(); DicomSegmentationObject dso = new DicomSegmentationObject(); SourceImage sourceDSOImage = dso.convert(tmpDSO.getAbsolutePath()); int numberOfFrames = sourceDSOImage.getNumberOfBufferedImages(); AttributeList dicomAttributes = PixelMedUtils.readAttributeListFromDicomFile(tmpDSO.getAbsolutePath()); String studyUID = Attribute.getSingleStringValueOrEmptyString(dicomAttributes, TagFromName.StudyInstanceUID); seriesUID = Attribute.getSingleStringValueOrEmptyString(dicomAttributes, TagFromName.SeriesInstanceUID); String imageUID = Attribute.getSingleStringValueOrEmptyString(dicomAttributes, TagFromName.SOPInstanceUID); String pngMaskDirectoryPath = baseDicomDirectory + "/studies/" + studyUID + "/series/" + seriesUID + "/images/" + imageUID + "/masks/"; String pngContourDirectoryPath = baseDicomDirectory + "/studies/" + studyUID + "/series/" + seriesUID + "/images/" + imageUID + "/contours/"; File pngMaskFilesDirectory = new File(pngMaskDirectoryPath); pngMaskFilesDirectory.mkdirs(); if ("true".equalsIgnoreCase(EPADConfig.getParamValue("GenerateDSOContours"))) { File pngContourFilesDirectory = new File(pngContourDirectoryPath); pngContourFilesDirectory.mkdirs(); } DICOMElementList dicomElementList = Dcm4CheeQueries.getDICOMElementsFromWADO(studyUID, seriesUID, imageUID); AttributeList dsoDICOMAttributes = PixelMedUtils.readDICOMAttributeList(tmpDSO); //SequenceAttribute segmentSequence = (SequenceAttribute) dsoDICOMAttributes.get(TagFromName.SegmentSequence); //AttributeTag t = TagFromName.SegmentNumber; //Attribute a = new UnsignedShortAttribute(t); int nonblankFrame = 0; String nonBlankImageUID = ""; List<DICOMElement> referencedSOPInstanceUIDDICOMElements = getDICOMElementsByCode(dicomElementList, PixelMedUtils.ReferencedSOPInstanceUIDCode); String[] segNums = SequenceAttribute .getArrayOfSingleStringValueOrEmptyStringOfNamedAttributeWithinSequenceItems(dsoDICOMAttributes, TagFromName.SegmentSequence, TagFromName.SegmentNumber); if (segNums == null || segNums.length <= 1) { String referencedSeriesUID = ""; log.info("Writing PNG masks for DSO " + imageUID + " number of referenced instances:" + referencedSOPInstanceUIDDICOMElements.size()); //dcm4CheeDatabaseOperations.getSeriesUIDForImage(referencedSOPInstanceUIDDICOMElements.get(0).value); for (int i = 0; i < referencedSOPInstanceUIDDICOMElements.size(); i++) { String referencedUID = dcm4CheeDatabaseOperations .getSeriesUIDForImage(referencedSOPInstanceUIDDICOMElements.get(i).value); if (referencedUID == null || referencedUID.length() == 0) { referencedSOPInstanceUIDDICOMElements.remove(i); i--; } else referencedSeriesUID = referencedUID; } log.info("Writing PNG masks for DSO " + imageUID + " number of valid referenced instances:" + referencedSOPInstanceUIDDICOMElements.size()); if (referencedSeriesUID == null || referencedSeriesUID.length() == 0) { try { // Best to delete this if the source series is missing ??? //SeriesReference seriesReference = new SeriesReference(EPADConfig.xnatUploadProjectID, null, studyUID, seriesUID); //DefaultEpadOperations.getInstance().deleteSeries(seriesReference, true); } catch (Exception x) { } throw new Exception("Referenced series for DSO " + seriesUID + " not found"); } int frameNumber = 0; File[] oldFiles = pngMaskFilesDirectory.listFiles(); // for (File oldFile: oldFiles) // { // try // { // if (oldFile.getName().contains("png")) // oldFile.delete(); // } catch (Exception x) {}; // } log.info("Writing PNG masks for DSO " + imageUID + " in series " + seriesUID + " DSOFile:" + dsoFile.getAbsolutePath() + " number of frames:" + numberOfFrames + " ..."); List<DCM4CHEEImageDescription> referencedImages = new ArrayList<DCM4CHEEImageDescription>(); List<DCM4CHEEImageDescription> imageDescriptions = dcm4CheeDatabaseOperations .getImageDescriptions(studyUID, referencedSeriesUID); //starting offset of instances (for series that doesn't start from 1) int instanceOffset = imageDescriptions.size(); Map<String, DCM4CHEEImageDescription> descMap = new HashMap<String, DCM4CHEEImageDescription>(); for (DCM4CHEEImageDescription imageDescription : imageDescriptions) { descMap.put(imageDescription.imageUID, imageDescription); if (imageDescription.instanceNumber < instanceOffset) instanceOffset = imageDescription.instanceNumber; } if (referencedSOPInstanceUIDDICOMElements.size() < imageDescriptions.size()) instanceOffset = 1; if (instanceOffset == 0) instanceOffset = 1; for (DICOMElement dicomElement : referencedSOPInstanceUIDDICOMElements) { String referencedImageUID = dicomElement.value; DCM4CHEEImageDescription dcm4cheeReferencedImageDescription = descMap.get(referencedImageUID); referencedImages.add(dcm4cheeReferencedImageDescription); } int index = 0; boolean onefound = false; int instanceCount = 0; log.info("Number of valid referenced Instances:" + referencedSOPInstanceUIDDICOMElements.size() + " instance offset:" + instanceOffset); for (DICOMElement dicomElement : referencedSOPInstanceUIDDICOMElements) { String referencedImageUID = dicomElement.value; DCM4CHEEImageDescription dcm4cheeReferencedImageDescription = referencedImages.get(index); index++; if (dcm4cheeReferencedImageDescription == null) { log.info("Did not find referenced image, seriesuid:" + referencedSeriesUID + " imageuid:" + referencedImageUID + " for DSO seriesUID:" + seriesUID + " DSO imageUID:" + imageUID); continue; } //log.info("Image dimensions - width " + bufferedImage.getWidth() + ", height " + bufferedImage.getHeight()); int instanceNumber = dcm4cheeReferencedImageDescription.instanceNumber; if (instanceNumber == 1 && onefound) // These are dicoms where all instance numbers are one ! { instanceCount++; instanceNumber = instanceCount; } if (instanceNumber == 1 && !onefound) { onefound = true; instanceCount = 1; } int refFrameNumber = instanceNumber - instanceOffset; // Frames 0-based, instances 1 or more if (refFrameNumber < 0) continue; log.info("FrameNumber:" + frameNumber + " refFrameNumber:" + refFrameNumber + " instance number:" + dcm4cheeReferencedImageDescription.instanceNumber); projectOperations.updateUserTaskStatus(username, TaskStatus.TASK_DSO_PNG_GEN, seriesUID, "Generating PNGs, frame:" + frameNumber, null, null); String pngMaskFilePath = pngMaskDirectoryPath + refFrameNumber + ".png"; try { log.info("buffered image "); BufferedImage bufferedImage = sourceDSOImage.getBufferedImage(frameNumber); log.info("buffered image " + bufferedImage.toString()); BufferedImage bufferedImageWithTransparency = generateTransparentImage(bufferedImage); log.info(" bufferedImageWithTransparency " + bufferedImageWithTransparency.toString()); if (nonBlank.get()) { nonblankFrame = refFrameNumber; nonBlankImageUID = dcm4cheeReferencedImageDescription.imageUID; } log.info(" nonblankFrame " + nonblankFrame); File pngMaskFile = new File(pngMaskFilePath); log.info(" pngMaskFile " + pngMaskFile.getAbsolutePath()); insertEpadFile(databaseOperations, pngMaskFilePath, pngMaskFile.length(), imageUID); log.info("Writing PNG mask file frame " + frameNumber + " of " + numberOfFrames + " for DSO " + imageUID + " in series " + seriesUID + " file:" + pngMaskFilePath + " nonBlank:" + nonBlank.get()); ImageIO.write(bufferedImageWithTransparency, "png", pngMaskFile); databaseOperations.updateEpadFileRow(pngMaskFilePath, PNGFileProcessingStatus.DONE, 0, ""); } catch (Exception e) { log.warning("Failure writing PNG mask file " + pngMaskFilePath + " for frame " + frameNumber + " of DSO " + imageUID + " in series " + seriesUID, e); } // Contours are currently never set to true, so never used if ("true".equalsIgnoreCase(EPADConfig.getParamValue("GenerateDSOContours"))) { String pngContourFilePath = pngContourDirectoryPath + refFrameNumber + ".png"; try { RunSystemCommand rsc = new RunSystemCommand("convert " + pngMaskFilePath + " -negate -edge 1 -negate " + pngContourFilePath); rsc.run(); } catch (Exception e) { log.warning("Failure writing PNG contour file " + pngContourFilePath + " for frame " + frameNumber + " of DSO " + imageUID + " in series " + seriesUID, e); } } frameNumber++; } } else { log.info("Oh my God, this is a stupid multi-segment DSO:" + seriesUID + " number of segments:" + segNums.length); SequenceAttribute perFrameSeq = (SequenceAttribute) dsoDICOMAttributes .get(TagFromName.PerFrameFunctionalGroupsSequence); int numFrames = perFrameSeq.getNumberOfItems(); String[] referencedSOPInstanceUIDs = new String[numFrames]; String[] segmentNumbers = new String[numFrames]; for (int i = 0; i < numFrames; i++) { AttributeList segAttrs = SequenceAttribute .getAttributeListFromSelectedItemWithinSequence(perFrameSeq, i); SequenceAttribute derImageSeq = (SequenceAttribute) segAttrs .get(TagFromName.DerivationImageSequence); AttributeList derImageAttrs = SequenceAttribute .getAttributeListFromSelectedItemWithinSequence(derImageSeq, 0); String[] refUDIDs = SequenceAttribute .getArrayOfSingleStringValueOrEmptyStringOfNamedAttributeWithinSequenceItems( derImageAttrs, TagFromName.SourceImageSequence, TagFromName.ReferencedSOPInstanceUID); String[] segNos = SequenceAttribute .getArrayOfSingleStringValueOrEmptyStringOfNamedAttributeWithinSequenceItems(segAttrs, TagFromName.SegmentIdentificationSequence, TagFromName.ReferencedSegmentNumber); referencedSOPInstanceUIDs[i] = refUDIDs[0]; segmentNumbers[i] = segNos[0]; } String referencedSeriesUID = dcm4CheeDatabaseOperations .getSeriesUIDForImage(referencedSOPInstanceUIDs[0]); if (referencedSeriesUID == null || referencedSeriesUID.length() == 0) throw new Exception("Referenced series for DSO " + seriesUID + " not found"); List<DCM4CHEEImageDescription> imageDescriptions = dcm4CheeDatabaseOperations .getImageDescriptions(studyUID, referencedSeriesUID); Map<String, DCM4CHEEImageDescription> descMap = new HashMap<String, DCM4CHEEImageDescription>(); for (DCM4CHEEImageDescription imageDescription : imageDescriptions) { descMap.put(imageDescription.imageUID, imageDescription); } numberOfFrames = referencedSOPInstanceUIDs.length; for (int i = 0; i < referencedSOPInstanceUIDs.length; i++) { DCM4CHEEImageDescription dcm4cheeReferencedImageDescription = descMap .get(referencedSOPInstanceUIDs[i]); int instanceNumber = dcm4cheeReferencedImageDescription.instanceNumber; int frameNumber = instanceNumber - 1; BufferedImage bufferedImage = sourceDSOImage.getBufferedImage(i); BufferedImage bufferedImageWithTransparency = generateTransparentImage(bufferedImage); if (nonBlank.get()) { nonblankFrame = frameNumber; nonBlankImageUID = dcm4cheeReferencedImageDescription.imageUID; } String pngMaskFilePath = pngMaskDirectoryPath + frameNumber + "_" + segmentNumbers[i] + ".png"; File pngMaskFile = new File(pngMaskFilePath); try { insertEpadFile(databaseOperations, pngMaskFilePath, pngMaskFile.length(), imageUID); log.info("Writing PNG mask file frame " + frameNumber + " of " + numberOfFrames + " for DSO " + imageUID + " in series " + seriesUID + " file:" + pngMaskFilePath + " nonBlank:" + nonBlank.get()); ImageIO.write(bufferedImageWithTransparency, "png", pngMaskFile); databaseOperations.updateEpadFileRow(pngMaskFilePath, PNGFileProcessingStatus.DONE, 0, ""); } catch (IOException e) { log.warning("Failure writing PNG mask file " + pngMaskFilePath + " for frame " + frameNumber + " of DSO " + imageUID + " in series " + seriesUID, e); } } } EpadDatabaseOperations epadDatabaseOperations = EpadDatabase.getInstance().getEPADDatabaseOperations(); List<EPADAIM> aims = epadDatabaseOperations.getAIMsByDSOSeries(seriesUID); for (EPADAIM aim : aims) { epadDatabaseOperations.updateAIMDSOFrameNo(aim.aimID, nonblankFrame); AIMUtil.updateDSOStartIndex(aim, nonblankFrame); } log.info("... finished writing PNG " + numberOfFrames + " masks for DSO image " + imageUID + " in series " + seriesUID + " nonBlankFrame:" + nonblankFrame); } catch (DicomException e) { log.warning("DICOM exception writing DSO PNG masks, series:" + seriesUID, e); throw new Exception("DICOM exception writing DSO PNG masks, series:" + seriesUID, e); } catch (IOException e) { log.warning("IO exception writing DSO PNG masks, series:" + seriesUID, e); throw new Exception("IO exception writing DSO PNG masks, series:" + seriesUID, e); } catch (Exception e) { log.warning("Exception writing DSO PNG masks, series:" + seriesUID, e); throw new Exception("Exception writing DSO PNG masks, series:" + seriesUID, e); } finally { try { tmpDSO.delete(); } catch (Exception e) { } ; } }
From source file:net.rptools.maptool.client.ui.ExportDialog.java
/** * This is the top-level screen-capture routine. It sends the resulting PNG * image to the location previously selected by the user. TODO: It currently * calls {@link MapTool#takeMapScreenShot()} for "normal" screenshots, but * that's just until this code is considered stable enough. * //from w ww . j a va 2s . co m * @throws Exception */ @SuppressWarnings("unused") public void screenCapture() throws Exception { MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.GeneratingScreenshot")); ExportRadioButtons type = ExportRadioButtons.getType(); Player.Role role; try { switch (type) { case TYPE_CURRENT_VIEW: // This uses the original screenshot code: I didn't want to touch it, so I need // to pass it the same parameter it took before. role = ExportRadioButtons.VIEW_GM.isChecked() ? Player.Role.GM : Player.Role.PLAYER; BufferedImage screenCap = MapTool.takeMapScreenShot(renderer.getPlayerView(role)); // since old screenshot code doesn't throw exceptions, look for null if (screenCap == null) { throw new Exception(I18N.getString("dialog.screenshot.error.failedImageGeneration")); } MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming")); ByteArrayOutputStream imageOut = new ByteArrayOutputStream(); try { ImageIO.write(screenCap, "png", imageOut); screenCap = null; // Free up the memory as soon as possible MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving")); exportLocation .putContent(new BufferedInputStream(new ByteArrayInputStream(imageOut.toByteArray()))); } finally { IOUtils.closeQuietly(imageOut); } MapTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved")); break; case TYPE_ENTIRE_MAP: switchToWaitPanel(); if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE") || interactPanel.isSelected("METHOD_IMAGE_WRITER")) { // Using a buffer in memory for the whole image try { final PlayerView view = preScreenshot(); final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next(); MapTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming")); BufferedImage image; if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")) { image = new BufferedImage(renderer.getWidth(), renderer.getHeight(), Transparency.OPAQUE); final Graphics2D g = image.createGraphics(); // g.setClip(0, 0, renderer.getWidth(), renderer.getHeight()); renderer.renderZone(g, view); g.dispose(); } else { image = new ZoneImageGenerator(renderer, view); } // putContent() can consume quite a bit of time; really should have a progress // meter of some kind here. exportLocation.putContent(pngWriter, image); if (image instanceof ZoneImageGenerator) { log.debug("ZoneImageGenerator() stats: " + image.toString()); } MapTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving")); } catch (Exception e) { MapTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.error.failedImageGeneration")); } finally { postScreenshot(); MapTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved")); } } else if (interactPanel.isSelected("METHOD_BACKGROUND")) { // We must call preScreenshot before creating the ZoneImageGenerator, because // ZoneImageGenerator uses the ZoneRenderer's bounds to set itself up MapTool.showError("This doesn't work! Try one of the other methods.", null); if (false) { // // Note: this implementation is the obvious way, which doesn't work, since // ZoneRenderer is part of the Swing component chain, and the threads get deadlocked. // // The suggested implementation by // "Reiger" at http://ubuntuforums.org/archive/index.php/t-1455270.html // might work... except that it would have to be part of ZoneRenderer // // The only way to make this really work is to pull the renderZone function // out of ZoneRenderer into a new class: call it ZoneRasterizer. Then make // ZoneRenderer create an instance of it, and patch up the code to make it // compatible. Then we can create an instance of ZoneRasterizer, and run it // in a separate thread, since it won't lock in any of the functions that // Swing uses. // class backscreenRender implements Runnable { public void run() { try { PlayerView view = preScreenshot(); final ZoneImageGenerator zoneImageGenerator = new ZoneImageGenerator(renderer, view); final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next(); exportLocation.putContent(pngWriter, zoneImageGenerator); // postScreenshot is called by the callback imageComplete() } catch (Exception e) { assert false : "Unhandled Exception in renderOffScreen: '" + e.getMessage() + "'"; } } } backscreenRender p = new backscreenRender(); new Thread(p).start(); repaint(); } } else { throw new Exception("Unknown rendering method!"); } break; default: throw new Exception(I18N.getString("dialog.screenshot.error.invalidDialogSettings")); } } catch (OutOfMemoryError e) { MapTool.showError("screenCapture() caught: Out Of Memory", e); } catch (Exception ex) { MapTool.showError("screenCapture() caught: ", ex); } }
From source file:com.t3.client.ui.ExportDialog.java
/** * This is the top-level screen-capture routine. It sends the resulting PNG * image to the location previously selected by the user. TODO: It currently * calls {@link TabletopTool#takeMapScreenShot()} for "normal" screenshots, but * that's just until this code is considered stable enough. * //ww w. j a va 2s . c o m * @throws Exception */ @SuppressWarnings("unused") public void screenCapture() throws Exception { TabletopTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.GeneratingScreenshot")); ExportRadioButtons type = ExportRadioButtons.getType(); Player.Role role; try { switch (type) { case TYPE_CURRENT_VIEW: // This uses the original screenshot code: I didn't want to touch it, so I need // to pass it the same parameter it took before. role = ExportRadioButtons.VIEW_GM.isChecked() ? Player.Role.GM : Player.Role.PLAYER; BufferedImage screenCap = TabletopTool.takeMapScreenShot(renderer.getPlayerView(role)); // since old screenshot code doesn't throw exceptions, look for null if (screenCap == null) { throw new Exception(I18N.getString("dialog.screenshot.error.failedImageGeneration")); } TabletopTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming")); ByteArrayOutputStream imageOut = new ByteArrayOutputStream(); try { ImageIO.write(screenCap, "png", imageOut); screenCap = null; // Free up the memory as soon as possible TabletopTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving")); exportLocation .putContent(new BufferedInputStream(new ByteArrayInputStream(imageOut.toByteArray()))); } finally { IOUtils.closeQuietly(imageOut); } TabletopTool.getFrame().setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved")); break; case TYPE_ENTIRE_MAP: switchToWaitPanel(); if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE") || interactPanel.isSelected("METHOD_IMAGE_WRITER")) { // Using a buffer in memory for the whole image try { final PlayerView view = preScreenshot(); final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next(); TabletopTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotStreaming")); BufferedImage image; if (interactPanel.isSelected("METHOD_BUFFERED_IMAGE")) { image = new BufferedImage(renderer.getWidth(), renderer.getHeight(), Transparency.OPAQUE); final Graphics2D g = image.createGraphics(); // g.setClip(0, 0, renderer.getWidth(), renderer.getHeight()); renderer.renderZone(g, view); g.dispose(); } else { image = new ZoneImageGenerator(renderer, view); } // putContent() can consume quite a bit of time; really should have a progress // meter of some kind here. exportLocation.putContent(pngWriter, image); if (image instanceof ZoneImageGenerator) { log.debug("ZoneImageGenerator() stats: " + image.toString()); } TabletopTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaving")); } catch (Exception e) { TabletopTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.error.failedImageGeneration")); } finally { postScreenshot(); TabletopTool.getFrame() .setStatusMessage(I18N.getString("dialog.screenshot.msg.screenshotSaved")); } } else if (interactPanel.isSelected("METHOD_BACKGROUND")) { // We must call preScreenshot before creating the ZoneImageGenerator, because // ZoneImageGenerator uses the ZoneRenderer's bounds to set itself up TabletopTool.showError("This doesn't work! Try one of the other methods.", null); if (false) { // // Note: this implementation is the obvious way, which doesn't work, since // ZoneRenderer is part of the Swing component chain, and the threads get deadlocked. // // The suggested implementation by // "Reiger" at http://ubuntuforums.org/archive/index.php/t-1455270.html // might work... except that it would have to be part of ZoneRenderer // // The only way to make this really work is to pull the renderZone function // out of ZoneRenderer into a new class: call it ZoneRasterizer. Then make // ZoneRenderer create an instance of it, and patch up the code to make it // compatible. Then we can create an instance of ZoneRasterizer, and run it // in a separate thread, since it won't lock in any of the functions that // Swing uses. // class backscreenRender implements Runnable { @Override public void run() { try { PlayerView view = preScreenshot(); final ZoneImageGenerator zoneImageGenerator = new ZoneImageGenerator(renderer, view); final ImageWriter pngWriter = ImageIO.getImageWritersByFormatName("png").next(); exportLocation.putContent(pngWriter, zoneImageGenerator); // postScreenshot is called by the callback imageComplete() } catch (Exception e) { assert false : "Unhandled Exception in renderOffScreen: '" + e.getMessage() + "'"; } } } backscreenRender p = new backscreenRender(); new Thread(p).start(); repaint(); } } else { throw new Exception("Unknown rendering method!"); } break; default: throw new Exception(I18N.getString("dialog.screenshot.error.invalidDialogSettings")); } } catch (OutOfMemoryError e) { TabletopTool.showError("screenCapture() caught: Out Of Memory", e); } catch (Exception ex) { TabletopTool.showError("screenCapture() caught: ", ex); } }
From source file:com.xauto.ux.Emf2.java
@SuppressWarnings("deprecation") public static void extractPicturesFromDoc(String docName) throws Exception { Document doc = new Document(docName + ".docx"); Integer emfOrWmfIndex = 1; Integer pngOrJpegIndex = 100; Integer bmpOrPictIndex = 10000; Integer otherIndex = 1000; String outDir = "out" + File.separator + docName + File.separator; FileUtils.forceMkdir(new File(outDir)); FileWriter html = new FileWriter(outDir + "out.html"); html.write(//from www . j ava2 s .c o m "<html>\n<head><meta http-equiv=\"x-ua-compatible\" content=\"IE=edge,chrome=1\"></head><body>\n"); for (AsposeDrawingType type : AsposeDrawingType.values()) { Node[] drawArray = doc.getChildNodes(type.code(), true).toArray(); int index = 0; logger.info("type={};count={}", type, drawArray.length); for (Node n : drawArray) { WordDrawing node = null; DrawingML dml = null; Shape s = null; if (n instanceof Shape) { s = (Shape) n; node = new WordDrawing(s); } else if (n instanceof DrawingML) { dml = (DrawingML) n; node = new WordDrawing(dml); } index++; IImageData img = node.getImageData(); BufferedImage bi = img.toImage(); AposeWordImageType asposeWordImageType = AposeWordImageType.fromCode(img.getImageType()); String extn = null; String trimmedDrawingName = node.getName().replace(" ", "") + index; ImageSize is = img.getImageSize(); long resolution = 600; int scale = 1000; Graphics2D gd = bi.createGraphics(); gd.getClipBounds(); int jpegQual = 70; boolean antiAlias = true; boolean highQualityRendering = true; try { extn = FileFormatUtil.imageTypeToExtension(img.getImageType()); } catch (IllegalArgumentException e) { extn = "unknown"; } String drawingName = node.getName(); if (StringUtils.isBlank(drawingName)) { if (node.getNode() instanceof Shape) { Shape s = (Shape) node.getNode(); Node cell = null; Node parent = s.getParentNode(); while (parent.getNodeType() != NodeType.ROW) { if (parent.getNodeType() == NodeType.CELL) { cell = parent; } parent = parent.getParentNode(); } Row picturesRow = (Row) parent; Row captionsRow = (Row) picturesRow.getPreviousSibling(); Node[] currentPicturesRowCells = picturesRow.getChildNodes(NodeType.CELL, true).toArray(); int foundIndex = 0; for (Node n : currentPicturesRowCells) { if (n == cell) { break; } foundIndex++; } Cell captionCell = (Cell) captionsRow.getChild(NodeType.CELL, foundIndex, true); StringBuilder sb = new StringBuilder(); Paragraph[] ps = captionCell.getParagraphs().toArray(); for (Paragraph p : ps) { Run[] rs = p.getRuns().toArray(); for (Run r : rs) { r.getDirectRunAttrsCount(); sb.append(r.getText()); } } drawingName = sb.toString().replace("SEQ Figure \\* ARABIC ", ""); } } logger.debug( "imageType={};name={};hasImage()={};imageByteSize={};isLink={};imageSize.Width={};imageSize.Height={};" + "imageSize.HorRes={};imageSize.VertRes={};imageSize.WPoints={};imageSize.HPoints={};" + "bufferedImageType={}; biHeight={}; biWidth={}; trimmedDrawingName={}; extn={};" + "" + "bufferedImageInfo={};drawInfo={}", asposeWordImageType, drawingName, img.hasImage(), img.getImageBytes() == null ? 0 : img.getImageBytes().length, img.isLink(), is.getWidthPixels(), is.getHeightPixels(), is.getHorizontalResolution(), is.getVerticalResolution(), is.getWidthPoints(), is.getHeightPoints(), AwtImageType.fromCode(bi.getType()), bi.getHeight(), bi.getWidth(), trimmedDrawingName, extn, bi.toString(), node.toString()); if (StringUtils.isBlank(node.getName())) { if (dml != null) { dml.getParentNode(); logger.debug("getAncestor={}", dml.getAncestor(DocumentProperty.class)); } else if (s != null) { s.getExpandedRunPr_IInline(54); logger.debug(s.toTxt() + s.getText()); @SuppressWarnings("unchecked") NodeCollection<Node> ns = s.getChildNodes(); while (ns.iterator().hasNext()) { Node n1 = (Node) ns.iterator().next(); n1.getText(); } logger.debug("shape={}", s.getAncestor(DocumentProperty.class)); s.getParentParagraph(); } } if (asposeWordImageType == AposeWordImageType.UNKNOWN) { otherIndex++; continue; } if (img == null || asposeWordImageType == AposeWordImageType.NO_IMAGE) { continue; } if (asposeWordImageType == AposeWordImageType.EMF || asposeWordImageType == AposeWordImageType.WMF) { ShapeRenderer sr = node.getShapeRenderer(); img.save(outDir + trimmedDrawingName + extn); PngOptions pngOptions = new PngOptions(); if (asposeWordImageType == AposeWordImageType.EMF) { EmfMetafileImage emf = new EmfMetafileImage(outDir + trimmedDrawingName + extn); emf.save(outDir + trimmedDrawingName + "_buffered_emf.png", pngOptions); } else { WmfMetafileImage wmf = new WmfMetafileImage(outDir + trimmedDrawingName + extn); wmf.save(outDir + trimmedDrawingName + "_buffered_emf.png", pngOptions); } trimmedDrawingName += "_" + scale + "_" + resolution + "_" + jpegQual + "_" + antiAlias + "_" + highQualityRendering; ImageSaveOptions pngSave = new ImageSaveOptions(com.aspose.words.SaveFormat.PNG); pngSave.setResolution(resolution); pngSave.setUseHighQualityRendering(highQualityRendering); pngSave.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML); pngSave.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE); pngSave.setUseAntiAliasing(antiAlias); pngSave.setScale((float) scale / 1000); ImageSaveOptions jpgSave = new ImageSaveOptions(SaveFormat.JPEG); jpgSave.setUseHighQualityRendering(true); jpgSave.setResolution(resolution); jpgSave.setJpegQuality(jpegQual); jpgSave.setScale((float) scale / 1000); sr.save(outDir + trimmedDrawingName + ".png", pngSave); BufferedImage savedPNG = ImageIO.read(new File(outDir + trimmedDrawingName + ".png")); BufferedImage resizedFromSaved = Scalr.resize(savedPNG, Method.ULTRA_QUALITY, Mode.FIT_TO_WIDTH, 435); BufferedImage resizedFromBi = Scalr.resize(bi, Method.ULTRA_QUALITY, Mode.FIT_TO_WIDTH, 435); ImageIO.write(bi, "png", new File(outDir + trimmedDrawingName + "_buffered.png")); ImageIO.write(resizedFromSaved, "png", new File(outDir + trimmedDrawingName + "_resized_from_saved_scalr_antialias_435.png")); ImageIO.write(resizedFromBi, "png", new File(outDir + trimmedDrawingName + "_resized_from_bi_scalr_antialias_435.png")); //sr.save(outDir+trimmedDrawingName+".jpg", jpgSave); html.write("\t<div>\n\t\t\n\t\t<br>\n\t\t<hr><p align=center>.SVG figure: " + trimmedDrawingName + "</p>\n\t\t<hr>\n\t\t<br>\n\t\t<br>\n\t\t<img src=\"" + trimmedDrawingName + ".svg\" width=\"100%\" />\n\t</div>\n"); //convertToSVG(outputDir + docId + "\\", trimmedDrawingName, extn); emfOrWmfIndex++; } else if (asposeWordImageType == AposeWordImageType.PNG || asposeWordImageType == AposeWordImageType.JPEG) { ShapeRenderer sr = node.getShapeRenderer(); ImageSaveOptions pngSave = new ImageSaveOptions(com.aspose.words.SaveFormat.PNG); pngSave.setResolution(resolution); pngSave.setUseHighQualityRendering(highQualityRendering); pngSave.setDmlRenderingMode(DmlRenderingMode.DRAWING_ML); pngSave.setDmlEffectsRenderingMode(DmlEffectsRenderingMode.FINE); pngSave.setUseAntiAliasing(antiAlias); pngSave.setScale((float) scale / 1000); img.save(outDir + trimmedDrawingName + extn); sr.save(outDir + trimmedDrawingName + "_DIRECT" + extn, pngSave); if (is.getHeightPoints() > 99) { html.write("\t<div>\n\t\t\n\t\t<br>\n\t\t<hr><p align=center>" + extn.toUpperCase() + " figure: " + trimmedDrawingName + "</p>\n\t\t<hr>\n\t\t<br>\n\t\t<br>\n\t\t<img src=\"" + trimmedDrawingName + extn + "\" width=\"100%\" />\n\t</div>\n"); } pngOrJpegIndex++; } else if (asposeWordImageType == AposeWordImageType.BMP || asposeWordImageType == AposeWordImageType.PICT) { img.save(outDir + bmpOrPictIndex + extn); bmpOrPictIndex++; } else { logger.info( "PICT type={}; isLink={}; isLinkOnly={}; imageSize={}; sourceFileName={}; hasImage={}", asposeWordImageType, img.isLink(), img.isLinkOnly(), img.getImageSize().getHorizontalResolution(), img.getSourceFullName(), img.hasImage()); } } } html.write("</body>\n</html>"); html.close(); }