List of usage examples for java.awt.image BufferedImage getType
public int getType()
From source file:com.occamlab.te.parsers.ImageParser.java
private static Node processFrame(ImageReader reader, int frame, NodeList nodes, PrintWriter logger) throws Exception { if (nodes.getLength() == 0) { return null; }// w ww .java 2 s.c o m String formatName = reader.getFormatName().toLowerCase(); // 2011-09-08 // PwD BufferedImage image = reader.read(frame); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { // System.out.println(node.getLocalName()); if (node.getLocalName().equals("type")) { node.setTextContent(formatName); // 2011-09-08 PwD was // reader.getFormatName().toLowerCase() } else if (node.getLocalName().equals("height")) { node.setTextContent(Integer.toString(image.getHeight())); } else if (node.getLocalName().equals("width")) { node.setTextContent(Integer.toString(image.getWidth())); } else if (node.getLocalName().equals("metadata")) { try { // 2011--08-23 PwD IIOMetadata metadata = reader.getImageMetadata(frame); if (metadata != null) { String format = ((Element) node).getAttribute("format"); if (format.length() == 0) { format = metadata.getNativeMetadataFormatName(); } Node tree = metadata.getAsTree(format); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(tree), new DOMResult(node)); } } catch (javax.imageio.IIOException e) { // 2011--08-23 PwD DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); String format = reader.getFormatName().toLowerCase(); String formatEltName = "javax_imageio_" + format + "_1.0"; Element formatElt = doc.createElement(formatEltName); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(formatElt), new DOMResult(node)); } } else if (node.getLocalName().equals("model")) { int imagetype = -1; String model = ((Element) node).getAttribute("value"); if (model.equals("MONOCHROME")) { imagetype = BufferedImage.TYPE_BYTE_BINARY; } else if (model.equals("GRAY")) { imagetype = BufferedImage.TYPE_BYTE_GRAY; } else if (model.equals("RGB")) { imagetype = BufferedImage.TYPE_3BYTE_BGR; } else if (model.equals("ARGB")) { imagetype = BufferedImage.TYPE_4BYTE_ABGR; } else { model = "CUSTOM"; } ((Element) node).setAttribute("value", model); BufferedImage buffImage = image; if (image.getType() != imagetype && imagetype != -1) { buffImage = new BufferedImage(image.getWidth(), image.getHeight(), imagetype); Graphics2D g2 = buffImage.createGraphics(); ImageTracker tracker = new ImageTracker(); boolean done = g2.drawImage(image, 0, 0, tracker); if (!done) { while (!tracker.done) { sleep(50); } } } processBufferedImage(buffImage, formatName, node.getChildNodes()); } else if (node.getLocalName().equals("transparency")) { // 2011-08-24 // PwD int transparency = image.getTransparency(); String transparencyName = null; switch (transparency) { case Transparency.OPAQUE: { transparencyName = "Opaque"; break; } case Transparency.BITMASK: { transparencyName = "Bitmask"; break; } case Transparency.TRANSLUCENT: { transparencyName = "Translucent"; break; } default: { transparencyName = "Unknown"; } } node.setTextContent(transparencyName); } else if (node.getLocalName().equals("base64Data")) { // 2011-09-08 // PwD String base64Data = getBase64Data(image, formatName, node); node.setTextContent(base64Data); } else { logger.println("ImageParser Error: Invalid tag " + node.getNodeName()); } } } return null; }
From source file:com.occamlab.te.parsers.ImageParser.java
private static void processBufferedImage(BufferedImage buffimage, String formatName, NodeList nodes) throws Exception { HashMap<Object, Object> bandMap = new HashMap<Object, Object>(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("subimage")) { Element e = (Element) node; int x = Integer.parseInt(e.getAttribute("x")); int y = Integer.parseInt(e.getAttribute("y")); int w = Integer.parseInt(e.getAttribute("width")); int h = Integer.parseInt(e.getAttribute("height")); processBufferedImage(buffimage.getSubimage(x, y, w, h), formatName, e.getChildNodes()); } else if (node.getLocalName().equals("checksum")) { CRC32 checksum = new CRC32(); Raster raster = buffimage.getRaster(); DataBufferByte buffer; if (node.getParentNode().getLocalName().equals("subimage")) { WritableRaster outRaster = raster.createCompatibleWritableRaster(); buffimage.copyData(outRaster); buffer = (DataBufferByte) outRaster.getDataBuffer(); } else { buffer = (DataBufferByte) raster.getDataBuffer(); }// w w w . j a v a 2s .co m int numbanks = buffer.getNumBanks(); for (int j = 0; j < numbanks; j++) { checksum.update(buffer.getData(j)); } Document doc = node.getOwnerDocument(); node.appendChild(doc.createTextNode(Long.toString(checksum.getValue()))); } else if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); if (sample.equals("all")) { bandMap.put(band, null); } else { HashMap<Object, Object> sampleMap = (HashMap<Object, Object>) bandMap.get(band); if (sampleMap == null) { if (!bandMap.containsKey(band)) { sampleMap = new HashMap<Object, Object>(); bandMap.put(band, sampleMap); } } sampleMap.put(Integer.decode(sample), new Integer(0)); } } else if (node.getLocalName().equals("transparentNodata")) { // 2011-08-24 // PwD String transparentNodata = checkTransparentNodata(buffimage, node); node.setTextContent(transparentNodata); } } } Iterator bandIt = bandMap.keySet().iterator(); while (bandIt.hasNext()) { String band_str = (String) bandIt.next(); int band_indexes[]; if (buffimage.getType() == BufferedImage.TYPE_BYTE_BINARY || buffimage.getType() == BufferedImage.TYPE_BYTE_GRAY) { band_indexes = new int[1]; band_indexes[0] = 0; } else { band_indexes = new int[band_str.length()]; for (int i = 0; i < band_str.length(); i++) { if (band_str.charAt(i) == 'A') band_indexes[i] = 3; if (band_str.charAt(i) == 'B') band_indexes[i] = 2; if (band_str.charAt(i) == 'G') band_indexes[i] = 1; if (band_str.charAt(i) == 'R') band_indexes[i] = 0; } } Raster raster = buffimage.getRaster(); java.util.HashMap sampleMap = (java.util.HashMap) bandMap.get(band_str); boolean addall = (sampleMap == null); if (sampleMap == null) { sampleMap = new java.util.HashMap(); bandMap.put(band_str, sampleMap); } int minx = raster.getMinX(); int maxx = minx + raster.getWidth(); int miny = raster.getMinY(); int maxy = miny + raster.getHeight(); int bands[][] = new int[band_indexes.length][raster.getWidth()]; for (int y = miny; y < maxy; y++) { for (int i = 0; i < band_indexes.length; i++) { raster.getSamples(minx, y, maxx, 1, band_indexes[i], bands[i]); } for (int x = minx; x < maxx; x++) { int sample = 0; for (int i = 0; i < band_indexes.length; i++) { sample |= bands[i][x] << ((band_indexes.length - i - 1) * 8); } Integer sampleObj = new Integer(sample); boolean add = addall; if (!addall) { add = sampleMap.containsKey(sampleObj); } if (add) { Integer count = (Integer) sampleMap.get(sampleObj); if (count == null) { count = new Integer(0); } count = new Integer(count.intValue() + 1); sampleMap.put(sampleObj, count); } } } } Node node = nodes.item(0); while (node != null) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (node.getLocalName().equals("count")) { String band = ((Element) node).getAttribute("bands"); String sample = ((Element) node).getAttribute("sample"); HashMap sampleMap = (HashMap) bandMap.get(band); Document doc = node.getOwnerDocument(); if (sample.equals("all")) { Node parent = node.getParentNode(); Node prevSibling = node.getPreviousSibling(); Iterator sampleIt = sampleMap.keySet().iterator(); Element countnode = null; int digits; String prefix; switch (buffimage.getType()) { case BufferedImage.TYPE_BYTE_BINARY: digits = 1; prefix = ""; break; case BufferedImage.TYPE_BYTE_GRAY: digits = 2; prefix = "0x"; break; default: prefix = "0x"; digits = band.length() * 2; } while (sampleIt.hasNext()) { countnode = doc.createElementNS(node.getNamespaceURI(), "count"); Integer sampleInt = (Integer) sampleIt.next(); Integer count = (Integer) sampleMap.get(sampleInt); if (band.length() > 0) { countnode.setAttribute("bands", band); } countnode.setAttribute("sample", prefix + HexString(sampleInt.intValue(), digits)); Node textnode = doc.createTextNode(count.toString()); countnode.appendChild(textnode); parent.insertBefore(countnode, node); if (sampleIt.hasNext()) { if (prevSibling != null && prevSibling.getNodeType() == Node.TEXT_NODE) { parent.insertBefore(prevSibling.cloneNode(false), node); } } } parent.removeChild(node); node = countnode; } else { Integer count = (Integer) sampleMap.get(Integer.decode(sample)); if (count == null) count = new Integer(0); Node textnode = doc.createTextNode(count.toString()); node.appendChild(textnode); } } } node = node.getNextSibling(); } }
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(/*w w w.ja va 2s .c om*/ "<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(); }
From source file:edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter.java
private byte[] getPixelsFromMaskFiles(List<String> maskFilePaths, List<String> dicomFilePaths, boolean removeEmpty) throws FileNotFoundException, IOException, DicomException { byte[] pixels = null; List<Integer> emptyFileIndex = new ArrayList<Integer>(); for (int i = 0; i < maskFilePaths.size(); i++) { File maskFile = new File(maskFilePaths.get(i)); BufferedImage maskImage = ImageIO.read(maskFile); // BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), // BufferedImage.TYPE_BYTE_BINARY); byte[] new_frame = ((DataBufferByte) maskImage.getRaster().getDataBuffer()).getData(); byte[] pixel_data = new_frame; long rgbLen = maskImage.getWidth() * maskImage.getHeight() * 4; long bwLen = maskImage.getWidth() * maskImage.getHeight() / 8; long greyLen = maskImage.getWidth() * maskImage.getHeight(); if (i == 0) { System.out.println("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen + " Actual tiff data len:" + new_frame.length); log.info("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen + " Actual tiff data len:" + new_frame.length); }// w w w . j a v a 2 s .c om boolean nonzerodata = false; // looks like 4 bytes/pixel, compress to 1 bit/pixel (else assume it is already 1 bit/pixel) if (new_frame.length == rgbLen) { if (i % 10 == 0) { System.out.println("Compressing tiff mask from rgb, mask:" + i); log.debug("Compressing tiff mask from rgb, mask:" + i); } int numpixels = new_frame.length / 4; int numbytes = numpixels / 8; pixel_data = new byte[numbytes]; for (int k = 0; k < numbytes; k++) { int index = k * 8 * 4; pixel_data[k] = 0; for (int l = 0; l < 4 * 8; l = l + 4) { if (new_frame[index + l] != 0) { int setBit = pixel_data[k] + (1 << (l / 4)); pixel_data[k] = (byte) setBit; nonzerodata = true; } } if (pixel_data[k] != 0) log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " compress rgb"); } // } // ml if else if (new_frame.length == greyLen || maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { if (maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { //if not indexed old version should work if (i % 10 == 0) { System.out.println("indexed tiff mask from rgb, mask:" + i); log.debug("indexed tiff mask from rgb, mask:" + i); } // pixel_data = ((DataBufferByte)convertRGBAToIndexed(maskImage).getRaster().getDataBuffer()).getData(); int numpixels = new_frame.length; pixel_data = new byte[numpixels]; log.info("maskfile data"); for (int k = 0; k < numpixels; k++) { pixel_data[k] = 0; if (new_frame[k] != 0) { pixel_data[k] = new_frame[k]; nonzerodata = true; } // byte red = (byte)((new_frame[index] * 8) / 256); // byte green = (byte)((new_frame[index+1] * 8) / 256); // byte blue = (byte)((new_frame[index+2] * 4) / 256); // pixel_data[k] =(byte) ((red << 5) | (green << 2) | blue); // for (int l = 0; l < 4; l=l+4) // { // if (new_frame[index + l] != 0) // { // int setBit = pixel_data[k] + (1 << (l)); // pixel_data[k] =(byte) setBit; // nonzerodata = true; // } // } if (pixel_data[k] != 0) log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " rgb "); } } else { if (i % 10 == 0) { System.out.println("Compressing tiff mask from grey, mask:" + i); log.debug("Compressing tiff mask from grey, mask:" + i); } int numpixels = new_frame.length; int numbytes = numpixels / 8; pixel_data = new byte[numbytes]; for (int k = 0; k < numbytes; k++) { int index = k * 8; pixel_data[k] = 0; for (int l = 0; l < 8; l++) { if (new_frame[index + l] != 0) { int setBit = pixel_data[k] + (1 << l); pixel_data[k] = (byte) setBit; nonzerodata = true; } } if (pixel_data[k] != 0) log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k]); } } } else //bw { if (i % 10 == 0) { System.out.println("Flipping odd bytes of bw tif, mask:" + i); log.debug("Flipping odd bytes of bw tif, mask:" + i); } int numbytes = maskImage.getWidth() * maskImage.getHeight() / 8; pixel_data = new byte[numbytes]; for (int k = 0; k < numbytes; k++) { // Flip every odd byte. why on earth do we need to do this? if (new_frame[k] != 0) nonzerodata = true; //flip if not indexed image (8 bit color) if (k % 2 != 0 && new_frame[k] != 0) { pixel_data[k] = 0; if ((new_frame[k] & 1) == 1) { int setBit = pixel_data[k] + 128; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 2) == 2) { int setBit = pixel_data[k] + 64; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 4) == 4) { int setBit = pixel_data[k] + 32; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 8) == 8) { int setBit = pixel_data[k] + 16; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 16) == 16) { int setBit = pixel_data[k] + 8; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 32) == 32) { int setBit = pixel_data[k] + 4; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 64) == 64) { int setBit = pixel_data[k] + 2; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 128) == 128) { int setBit = pixel_data[k] + 1; pixel_data[k] = (byte) setBit; } if (new_frame[k] != 0) System.out.println("Old byte:" + new_frame[k] + " New byte:" + pixel_data[k]); } else pixel_data[k] = new_frame[k]; if (pixel_data[k] != 0) log.info("maskfile bw-rgb" + i + ": " + k + " pixel:" + pixel_data[k]); } } log.info("maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:" + pixel_data.length + " nonzero data:" + nonzerodata); if (!nonzerodata && removeEmpty) { log.debug("Nodata - maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:" + pixel_data.length); emptyFileIndex.add(i); continue; } if (pixels == null) { //pixels = new_frame.clone(); pixels = pixel_data; } else { byte[] temp = new byte[pixels.length + pixel_data.length]; System.arraycopy(pixels, 0, temp, 0, pixels.length); System.arraycopy(pixel_data, 0, temp, pixels.length, pixel_data.length); //pixels = temp.clone(); pixels = temp; } } for (int i = 0; i < emptyFileIndex.size(); i++) { int index = emptyFileIndex.get(i); log.info("Removing dicom " + (dicomAttributes.length - index - 1)); dicomFilePaths.remove(dicomAttributes.length - index - 1); dicomAttributes[index] = null; } // for (int i = 0; i < emptyFileIndex.size(); i++) // { // int index = emptyFileIndex.get(i); // log.info("Removing dicom " + (maskFilePaths.size() - index - 1)); // dicomFilePaths.remove(maskFilePaths.size() - index - 1); // DicomFiles are in reverse order for!!! // } if (pixels == null) throw new RuntimeException("The DSO has all empty frames"); log.info("Number of pixels:" + pixels.length + " dicoms:" + dicomFilePaths.size()); return pixels; }
From source file:edu.stanford.epad.common.pixelmed.TIFFMasksToDSOConverter.java
/** * get pixels and fill firstFrame for dso * @param maskFilePaths//from w w w .j a va 2s. com * @param dicomFilePaths * @param removeEmpty * @return * @throws FileNotFoundException * @throws IOException * @throws DicomException */ private byte[] getPixelsFromMaskFiles(List<String> maskFilePaths, List<String> dicomFilePaths, boolean removeEmpty, String dsoUID) throws FileNotFoundException, IOException, DicomException { Integer firstFrame = -1; byte[] pixels = null; List<Integer> emptyFileIndex = new ArrayList<Integer>(); for (int i = 0; i < maskFilePaths.size(); i++) { File maskFile = new File(maskFilePaths.get(i)); BufferedImage maskImage = ImageIO.read(maskFile); // BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), // BufferedImage.TYPE_BYTE_BINARY); byte[] new_frame = ((DataBufferByte) maskImage.getRaster().getDataBuffer()).getData(); byte[] pixel_data = new_frame; long rgbLen = maskImage.getWidth() * maskImage.getHeight() * 4; long bwLen = maskImage.getWidth() * maskImage.getHeight() / 8; long greyLen = maskImage.getWidth() * maskImage.getHeight(); if (i == 0) { System.out.println("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen + " Actual tiff data len:" + new_frame.length); log.info("Expected length, RGB:" + rgbLen + " BW:" + bwLen + " Grey:" + greyLen + " Actual tiff data len:" + new_frame.length); } boolean nonzerodata = false; // looks like 4 bytes/pixel, compress to 1 bit/pixel (else assume it is already 1 bit/pixel) if (new_frame.length == rgbLen) { if (i % 10 == 0) { System.out.println("Compressing tiff mask from rgb, mask:" + i); log.debug("Compressing tiff mask from rgb, mask:" + i); } int numpixels = new_frame.length / 4; int numbytes = numpixels / 8; pixel_data = new byte[numbytes]; for (int k = 0; k < numbytes; k++) { int index = k * 8 * 4; pixel_data[k] = 0; for (int l = 0; l < 4 * 8; l = l + 4) { if (new_frame[index + l] != 0) { int setBit = pixel_data[k] + (1 << (l / 4)); pixel_data[k] = (byte) setBit; nonzerodata = true; } } if (pixel_data[k] != 0) log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " compress rgb"); } // } // ml if else if (new_frame.length == greyLen || maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { if (maskImage.getType() == BufferedImage.TYPE_BYTE_INDEXED) { //if not indexed old version should work if (i % 10 == 0) { System.out.println("indexed tiff mask from rgb, mask:" + i); log.debug("indexed tiff mask from rgb, mask:" + i); } // pixel_data = ((DataBufferByte)convertRGBAToIndexed(maskImage).getRaster().getDataBuffer()).getData(); int numpixels = new_frame.length; pixel_data = new byte[numpixels]; log.info("maskfile data"); for (int k = 0; k < numpixels; k++) { pixel_data[k] = 0; if (new_frame[k] != 0) { pixel_data[k] = new_frame[k]; nonzerodata = true; } // byte red = (byte)((new_frame[index] * 8) / 256); // byte green = (byte)((new_frame[index+1] * 8) / 256); // byte blue = (byte)((new_frame[index+2] * 4) / 256); // pixel_data[k] =(byte) ((red << 5) | (green << 2) | blue); // for (int l = 0; l < 4; l=l+4) // { // if (new_frame[index + l] != 0) // { // int setBit = pixel_data[k] + (1 << (l)); // pixel_data[k] =(byte) setBit; // nonzerodata = true; // } // } if (pixel_data[k] != 0) log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k] + " rgb "); } } else { if (i % 10 == 0) { System.out.println("Compressing tiff mask from grey, mask:" + i); log.debug("Compressing tiff mask from grey, mask:" + i); } int numpixels = new_frame.length; int numbytes = numpixels / 8; pixel_data = new byte[numbytes]; for (int k = 0; k < numbytes; k++) { int index = k * 8; pixel_data[k] = 0; for (int l = 0; l < 8; l++) { if (new_frame[index + l] != 0) { int setBit = pixel_data[k] + (1 << l); pixel_data[k] = (byte) setBit; nonzerodata = true; } } if (pixel_data[k] != 0) log.info("maskfile" + i + ": " + k + " pixel:" + pixel_data[k]); } } } else //bw { if (i % 10 == 0) { System.out.println("Flipping odd bytes of bw tif, mask:" + i); log.debug("Flipping odd bytes of bw tif, mask:" + i); } int numbytes = maskImage.getWidth() * maskImage.getHeight() / 8; pixel_data = new byte[numbytes]; for (int k = 0; k < numbytes; k++) { // Flip every odd byte. why on earth do we need to do this? if (new_frame[k] != 0) nonzerodata = true; //flip if not indexed image (8 bit color) if (k % 2 != 0 && new_frame[k] != 0) { pixel_data[k] = 0; if ((new_frame[k] & 1) == 1) { int setBit = pixel_data[k] + 128; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 2) == 2) { int setBit = pixel_data[k] + 64; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 4) == 4) { int setBit = pixel_data[k] + 32; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 8) == 8) { int setBit = pixel_data[k] + 16; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 16) == 16) { int setBit = pixel_data[k] + 8; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 32) == 32) { int setBit = pixel_data[k] + 4; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 64) == 64) { int setBit = pixel_data[k] + 2; pixel_data[k] = (byte) setBit; } if ((new_frame[k] & 128) == 128) { int setBit = pixel_data[k] + 1; pixel_data[k] = (byte) setBit; } if (new_frame[k] != 0) System.out.println("Old byte:" + new_frame[k] + " New byte:" + pixel_data[k]); } else pixel_data[k] = new_frame[k]; if (pixel_data[k] != 0) log.info("maskfile bw-rgb" + i + ": " + k + " pixel:" + pixel_data[k]); } } log.info("maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:" + pixel_data.length + " nonzero data:" + nonzerodata); if (!nonzerodata && removeEmpty) { log.debug("Nodata - maskfile" + i + ": " + maskFilePaths.get(i) + " frame_length:" + pixel_data.length); emptyFileIndex.add(i); continue; } if (nonzerodata) { Integer reverseNum = maskFilePaths.size() - i - 1; if (firstFrame == -1 || reverseNum < firstFrame) { firstFrame = reverseNum; log.info("setting firstframe:" + firstFrame); } } if (pixels == null) { //pixels = new_frame.clone(); pixels = pixel_data; } else { byte[] temp = new byte[pixels.length + pixel_data.length]; System.arraycopy(pixels, 0, temp, 0, pixels.length); System.arraycopy(pixel_data, 0, temp, pixels.length, pixel_data.length); //pixels = temp.clone(); pixels = temp; } } //update the firstframe for this dso log.info("first frame for dso:" + dsoUID + " is " + firstFrame); firstFrames.put(dsoUID, firstFrame); for (int i = 0; i < emptyFileIndex.size(); i++) { int index = emptyFileIndex.get(i); log.info("Removing dicom " + (dicomAttributes.length - index - 1)); dicomFilePaths.remove(dicomAttributes.length - index - 1); dicomAttributes[index] = null; } // for (int i = 0; i < emptyFileIndex.size(); i++) // { // int index = emptyFileIndex.get(i); // log.info("Removing dicom " + (maskFilePaths.size() - index - 1)); // dicomFilePaths.remove(maskFilePaths.size() - index - 1); // DicomFiles are in reverse order for!!! // } if (pixels == null) throw new RuntimeException("The DSO has all empty frames"); log.info("Number of pixels:" + pixels.length + " dicoms:" + dicomFilePaths.size()); return pixels; }
From source file:wsserver.EKF1TimerSessionBean.java
private boolean postMultipartSectUpd(List<CbEkfgroupUpd1csectToBx> uswps) { String charset = "UTF-8"; String requestURL = systemURL + "bitrix/ekflibraries/corpbus/manipulate_data.php"; boolean reply = true; String sreply = ""; if (uswps.isEmpty()) return reply; long allFileSize = 0; String logStr = "Upd sect cnt=" + uswps.size() + ". "; CloseableHttpClient httpclient = HttpClients.createDefault(); try {//from ww w . ja v a 2s . co m MultipartUtility multipart = new MultipartUtility(requestURL, charset); HttpPost httppost = new HttpPost(requestURL); MultipartEntityBuilder reqBuilder = MultipartEntityBuilder.create(); multipart.addHeaderField("User-Agent", "CodeJava"); httppost.addHeader("User-Agent", "CodeJava"); multipart.addHeaderField("Test-Header", "Header-Value"); int index = 0; multipart.addFormField("OTYPE", "UPDATE"); reqBuilder.addPart("OTYPE", new StringBody("UPDATE", ContentType.TEXT_PLAIN)); multipart.addFormField("ENTITY", "1CSECT"); reqBuilder.addPart("ENTITY", new StringBody("1CSECT", ContentType.TEXT_PLAIN)); int ocnt = uswps.size(); multipart.addFormField("OCNT", "" + ocnt); reqBuilder.addPart("OCNT", new StringBody("" + ocnt, ContentType.TEXT_PLAIN)); //String logStr=""; for (CbEkfgroupUpd1csectToBx npwp : uswps) { multipart.addFormField("SID" + index, npwp.getSid()); reqBuilder.addPart("SID" + index, new StringBody(npwp.getSid(), ContentType.TEXT_PLAIN)); //if(!npwp.getSid().equals(npwp.getCbBxgroupId())) // multipart.addFormField("SETSID"+index, "1"); //else // multipart.addFormField("SETSID"+index, "0"); //multipart.addFormField("NEWSID"+index, npwp.getCbBxgroupId()); logStr += "[" + index + "] NAME " + npwp.getBxname() + "," + npwp.getF1cname() + "," + npwp.getBxparentId() + "," + npwp.getF1cparentId(); if (!npwp.getBxname().equals(npwp.getF1cname())) { multipart.addFormField("SETSNAME" + index, "1"); reqBuilder.addPart("SETSNAME" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSNAME" + index, "0"); reqBuilder.addPart("SETSNAME" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } if (!npwp.getBxparentId().equals(npwp.getF1cparentId())) { multipart.addFormField("SETSGRXMLID" + index, "1"); reqBuilder.addPart("SETSGRXMLID" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSGRXMLID" + index, "0"); reqBuilder.addPart("SETSGRXMLID" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("SNAME" + index, npwp.getF1cname()); reqBuilder.addPart("SNAME" + index, new StringBody(npwp.getF1cname(), ContentType.TEXT_PLAIN)); multipart.addFormField("SGRXMLID" + index, npwp.getF1cparentId()); reqBuilder.addPart("SGRXMLID" + index, new StringBody(npwp.getF1cparentId(), ContentType.TEXT_PLAIN)); boolean error_file_operation = false, uploadFiles = true; long sectFilesSize = 0; boolean tooLargeDsc = false, tooLargeGb = false, tooLargeDoc = false; ArrayList<String> dscFiles = new ArrayList<String>(); try { if (!npwp.getBxDescriptsJson().equals(npwp.getF1cDescriptsJson())) { //logStr+="["+npwp.getF1cDescriptsJson()+"]"; JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cDescriptsJson())); JsonObject jo = jsonReader.readObject(); int dcount = 0; logStr += "cnt=" + jo.getString("dc", "0"); for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) { logStr += ("[" + i + "]"); try { if (jo.getString("fp" + i).length() > 0 && uploadFiles) { File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/")); if (f.length() <= maxPostedFileSize && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) { dscFiles.add(jo.getString("fp" + i).replace("\\", "/")); multipart.addFormField("FDSC" + index + "DSC" + dcount, jo.getString("dsc" + i)); multipart.addFormField("FDSC" + index + "FN" + dcount, jo.getString("fn" + i)); reqBuilder.addPart("FDSC" + index + "DSC" + dcount, new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN)); reqBuilder.addPart("FDSC" + index + "FN" + dcount, new StringBody(jo.getString("fn" + i), ContentType.TEXT_PLAIN)); sectFilesSize += f.length(); dcount++; } else { tooLargeDsc = true; logStr += "Too large " + jo.getString("fp" + i); } } } catch (Exception fle) { //sectFilesSize=0; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error dsc file operation!!! " + fle); } } if (dcount > 0) { multipart.addFormField("FDSCDC" + index, "" + dcount); reqBuilder.addPart("FDSCDC" + index, new StringBody("" + dcount, ContentType.TEXT_PLAIN)); } } } catch (Exception fle) { logStr += (npwp.getF1cname() + " Error F1cDescriptsJson parse operation!!! " + fle + "[[" + npwp.getF1cDescriptsJson() + "]]"); } ArrayList<String> gbFiles = new ArrayList<String>(); try { if (!npwp.getBxGabaritsJson().equals(npwp.getF1cGabaritsJson())) { //logStr+="["+npwp.getF1cGabaritsJson()+"]"; JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cGabaritsJson())); JsonObject jo = jsonReader.readObject(); int dcount = 0; logStr += "cnt=" + jo.getString("dc", "0"); for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) { logStr += ("[" + i + "]"); try { if (jo.getString("fp" + i).length() > 0 && uploadFiles) { File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/")); if (f.length() <= maxPostedFileSize && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) { gbFiles.add(jo.getString("fp" + i).replace("\\", "/")); multipart.addFormField("FGB" + index + "DSC" + dcount, jo.getString("dsc" + i)); multipart.addFormField("FGB" + index + "FN" + dcount, jo.getString("fn" + i)); reqBuilder.addPart("FGB" + index + "DSC" + dcount, new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN)); reqBuilder.addPart("FGB" + index + "FN" + dcount, new StringBody(jo.getString("fn" + i), ContentType.TEXT_PLAIN)); sectFilesSize += f.length(); dcount++; logStr += "[=" + dcount + "=]"; } else { tooLargeGb = true; logStr += "Too large " + jo.getString("fp" + i); } } } catch (Exception fle) { //sectFilesSize=0; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error dsc file operation!!! " + fle); } } if (dcount > 0) { multipart.addFormField("FGBDC" + index, "" + dcount); reqBuilder.addPart("FGBDC" + index, new StringBody("" + dcount, ContentType.TEXT_PLAIN)); } } } catch (Exception fle) { logStr += (npwp.getF1cname() + " Error F1cGabaritsJson parse operation!!! " + fle + "[[" + npwp.getF1cGabaritsJson() + "]]"); } ArrayList<String> docFiles = new ArrayList<String>(); try { if (!npwp.getBxDocsJson().equals(npwp.getF1cDocsJson())) { //logStr+="["+npwp.getF1cDocsJson()+"]"; JsonReader jsonReader = Json.createReader(new StringReader(npwp.getF1cDocsJson())); JsonObject jo = jsonReader.readObject(); int dcount = 0; logStr += "cnt=" + jo.getString("dc", "0"); for (int i = 0; i < Tools.parseInt(jo.getString("dc", "0"), 0); i++) { logStr += ("[" + i + "]"); try { if (jo.getString("fp" + i).length() > 0 && uploadFiles) { File f = new File(mountImgPath + jo.getString("fp" + i).replace("\\", "/")); if (f.length() <= maxPostedDocFileSize && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) { docFiles.add(jo.getString("fp" + i).replace("\\", "/")); multipart.addFormField("FDOC" + index + "DSC" + dcount, jo.getString("dsc" + i)); //logStr+=("FDOC"+index+"FN+"+dcount+"="+jo.getString("fn"+i)); multipart.addFormField("FDOC" + index + "FN" + dcount, jo.getString("fn" + i)); reqBuilder.addPart("FDOC" + index + "DSC" + dcount, new StringBody(jo.getString("dsc" + i), ContentType.TEXT_PLAIN)); reqBuilder.addPart("FDOC" + index + "FN" + dcount, new StringBody(StringEscapeUtils.escapeJava(jo.getString("fn" + i)), ContentType.TEXT_PLAIN)); sectFilesSize += f.length(); dcount++; } else { tooLargeDoc = true; logStr += "Too large " + jo.getString("fp" + i); } } } catch (Exception fle) { //sectFilesSize=0; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error doc file operation!!! " + fle); } } if (dcount > 0) { multipart.addFormField("FDOCDC" + index, "" + dcount); reqBuilder.addPart("FDOCDC" + index, new StringBody("" + dcount, ContentType.TEXT_PLAIN)); } } } catch (Exception fle) { logStr += (npwp.getF1cname() + " Error F1cDocsJson parse operation!!! " + fle + "[[" + npwp.getF1cDocsJson() + "]]"); } try { if (npwp.getF1cPicture().length() > 0 && npwp.getBxPicture().length() == 0 && uploadFiles) { File f = new File(mountImgPath + npwp.getF1cPicture().replace("\\", "/")); if (f.length() <= maxPostedFileSize && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) { sectFilesSize += f.length(); } } } catch (Exception fle) { //sectFilesSize=0; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cPicture file operation!!! " + fle); } try { if (npwp.getF1cMcatalog().length() > 0 && npwp.getBxMcatalog().length() == 0 && uploadFiles) { File f = new File(mountImgPath + npwp.getF1cMcatalog().replace("\\", "/")); if (f.length() <= maxPostedDocFileSize && ((allFileSize + sectFilesSize + f.length()) < maxPostFilePartSize)) { sectFilesSize += f.length(); } } } catch (Exception fle) { //sectFilesSize=0; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cMcatalog file operation!!! " + fle); } if ((allFileSize + sectFilesSize) > maxPostFilePartSize) { logStr += ("NAME " + npwp.getF1cname() + " - too big sect files sizes summ!!!"); //continue; } else { if (!error_file_operation) { try { if (!npwp.getF1cPicture().equals(npwp.getBxPicture()) && uploadFiles) { File f = new File(mountImgPath + npwp.getF1cPicture().replace("\\", "/")); if (f.length() <= maxPostedFileSize && ((allFileSize + f.length()) < maxPostFilePartSize)) { logStr += ",getF1cPicture " + npwp.getF1cPicture() + "fname=" + f.getName() + ",fpath=" + f.getPath() + ",flength=[" + f.length() + "]"; allFileSize += f.length(); try { BufferedImage originalImage = ImageIO.read(f); if ((originalImage.getHeight() > 400 || originalImage.getWidth() > 400) && false) { int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType(); BufferedImage resizeImageJpg = resizeImage(originalImage, type); logStr += "Not require resize"; //multipart.addFilePart("PICTURE"+index, (resizeImageJpg) ); //multipart.addFormField("SETPICTURE"+index, "1"); } else { logStr += "Not require resize"; multipart.addFilePart("PICTURE" + index, (f)); multipart.addFormField("SETPICTURE" + index, "1"); multipart.addFormField("PICTURE_PATH" + index, StringEscapeUtils.escapeJava(npwp.getF1cPicture())); reqBuilder.addPart("PICTURE" + index, new FileBody(f)); reqBuilder.addPart("SETPICTURE" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } } catch (Exception frle) { logStr += "Error resizing" + frle; multipart.addFilePart("PICTURE" + index, (f)); multipart.addFormField("SETPICTURE" + index, "1"); multipart.addFormField("PICTURE_PATH" + index, StringEscapeUtils.escapeJava(npwp.getF1cPicture())); reqBuilder.addPart("PICTURE" + index, new FileBody(f)); reqBuilder.addPart("SETPICTURE" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } } else { multipart.addFormField("SETPICTURE" + index, "0"); reqBuilder.addPart("SETPICTURE" + index, new StringBody("0", ContentType.TEXT_PLAIN)); logStr += ",getF1cPicture " + f.length() + " more " + maxPostedFileSize / 1000000 + "Mbytes or too big allFileSize"; } } } catch (Exception fle) { error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cPicture file operation!!! " + fle); } try { if (npwp.getF1cMcatalog().length() > 0 && npwp.getBxMcatalog().length() == 0 && uploadFiles) { File f = new File(mountImgPath + npwp.getF1cMcatalog().replace("\\", "/")); if (f.length() <= maxPostedDocFileSize && ((allFileSize + f.length()) < maxPostFilePartSize)) { logStr += ",getF1cMcatalog " + npwp.getF1cMcatalog(); allFileSize += f.length(); multipart.addFilePart("MASTER_CATALOG" + index, (f)); multipart.addFormField("SETMASTER_CATALOG" + index, "1"); reqBuilder.addPart("MASTER_CATALOG" + index, new FileBody(f)); reqBuilder.addPart("SETMASTER_CATALOG" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETMASTER_CATALOG" + index, "0"); reqBuilder.addPart("SETMASTER_CATALOG" + index, new StringBody("0", ContentType.TEXT_PLAIN)); logStr += ",getF1cMcatalog " + f.length() + " more " + maxPostedDocFileSize / 1000000 + "Mbytes or too big allFileSize"; } } } catch (Exception fle) { error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error getF1cMcatalog file operation!!! " + fle); } int succFilesCount = 0; for (int i = 0; i < dscFiles.size(); i++) { try { if (dscFiles.get(i).length() > 0 && uploadFiles) { File f = new File(mountImgPath + dscFiles.get(i)); long lastFSize = 0; lastFSize = f.length(); if (lastFSize <= maxPostedFileSize && ((allFileSize + lastFSize) < maxPostFilePartSize)) { logStr += ",dscFiles " + dscFiles.get(i); multipart.addFilePart("FDSC" + index + "FP" + i, (f)); multipart.addFormField("FDSC" + index + "FPSET" + i, "1"); reqBuilder.addPart("FDSC" + index + "FP" + i, new FileBody(f)); reqBuilder.addPart("FDSC" + index + "FPSET" + i, new StringBody("1", ContentType.TEXT_PLAIN)); succFilesCount++; allFileSize += lastFSize; } else { //if(lastFSize>maxPostedFileSize) // succFilesCount++; tooLargeDsc = true; multipart.addFormField("FDSC" + index + "FPSET" + i, "0"); reqBuilder.addPart("FDSC" + index + "FPSET" + i, new StringBody("0", ContentType.TEXT_PLAIN)); logStr += ",dscFiles " + f.length() + " more " + maxPostedFileSize / 1000000 + "Mbytes or too big allFileSize"; } } } catch (Exception fle) { tooLargeDsc = true; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error dscFiles file operation!!! " + fle); } } if (!tooLargeDsc) { if ((dscFiles.size() <= 0) || ((succFilesCount >= 1) && (succFilesCount >= (int) (dscFiles.size() / 2)))) { if (!npwp.getBxDescriptsJson().equals(npwp.getF1cDescriptsJson())) { multipart.addFormField("SETDESCRIPTS_JSON" + index, "1"); reqBuilder.addPart("SETDESCRIPTS_JSON" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETDESCRIPTS_JSON" + index, "0"); reqBuilder.addPart("SETDESCRIPTS_JSON" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("DESCRIPTS_JSON" + index, StringEscapeUtils.escapeJava(npwp.getF1cDescriptsJson())); reqBuilder.addPart("DESCRIPTS_JSON" + index, new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cDescriptsJson()), ContentType.TEXT_PLAIN)); } else logStr += ("NAME " + npwp.getF1cname() + " - Error dscFiles count!!! "); } succFilesCount = 0; for (int i = 0; i < gbFiles.size(); i++) { try { if (gbFiles.get(i).length() > 0 && uploadFiles) { File f = new File(mountImgPath + gbFiles.get(i)); long lastFSize = 0; lastFSize = f.length(); if (lastFSize <= maxPostedFileSize && ((allFileSize + lastFSize) < maxPostFilePartSize)) { logStr += ",gbFiles " + gbFiles.get(i); multipart.addFilePart("FGB" + index + "FP" + i, (f)); multipart.addFormField("FGB" + index + "FPSET" + i, "1"); reqBuilder.addPart("FGB" + index + "FP" + i, new FileBody(f)); reqBuilder.addPart("FGB" + index + "FPSET" + i, new StringBody("1", ContentType.TEXT_PLAIN)); succFilesCount++; allFileSize += lastFSize; } else { //if(lastFSize>maxPostedFileSize) // succFilesCount++; tooLargeGb = true; multipart.addFormField("FGB" + index + "FPSET" + i, "0"); reqBuilder.addPart("FGB" + index + "FPSET" + i, new StringBody("0", ContentType.TEXT_PLAIN)); logStr += ",gbFiles " + f.length() + " more " + maxPostedFileSize / 1000000 + "Mbytes or too big allFileSize"; } } } catch (Exception fle) { tooLargeGb = true; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error gbrFiles file operation!!! " + fle); } } if (!tooLargeGb) { if ((gbFiles.size() <= 0) || ((succFilesCount >= 1) && (succFilesCount >= (int) (gbFiles.size() / 2)))) { if (!npwp.getBxGabaritsJson().equals(npwp.getF1cGabaritsJson())) { multipart.addFormField("SETGABARITS_JSON" + index, "1"); reqBuilder.addPart("SETGABARITS_JSON" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETGABARITS_JSON" + index, "0"); reqBuilder.addPart("SETGABARITS_JSON" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("GABARITS_JSON" + index, StringEscapeUtils.escapeJava(npwp.getF1cGabaritsJson())); reqBuilder.addPart("GABARITS_JSON" + index, new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cGabaritsJson()), ContentType.TEXT_PLAIN)); } else logStr += ("NAME " + npwp.getF1cname() + " - Error gbrFiles count!!! "); } succFilesCount = 0; for (int i = 0; i < docFiles.size(); i++) { try { if (docFiles.get(i).length() > 0 && uploadFiles) { File f = new File(mountImgPath + docFiles.get(i)); long lastFSize = 0; lastFSize = f.length(); if (lastFSize <= maxPostedDocFileSize && ((allFileSize + lastFSize) < maxPostFilePartSize)) { logStr += ",docFiles " + docFiles.get(i); multipart.addFilePart("FDOC" + index + "FP" + i, (f)); multipart.addFormField("FDOC" + index + "FPSET" + i, "1"); reqBuilder.addPart("FDOC" + index + "FP" + i, new FileBody(f)); reqBuilder.addPart("FDOC" + index + "FPSET" + i, new StringBody("1", ContentType.TEXT_PLAIN)); succFilesCount++; allFileSize += lastFSize; } else { //if(lastFSize>maxPostedFileSize) // succFilesCount++; tooLargeDoc = true; multipart.addFormField("FDOC" + index + "FPSET" + i, "0"); reqBuilder.addPart("FDOC" + index + "FPSET" + i, new StringBody("0", ContentType.TEXT_PLAIN)); logStr += ",docFiles " + f.length() + " more " + maxPostedDocFileSize / 1000000 + "Mbytes or too big allFileSize"; } } } catch (Exception fle) { tooLargeDoc = true; error_file_operation = true; logStr += ("NAME " + npwp.getF1cname() + " - Error docFiles file operation!!! " + fle); } } if (!tooLargeDoc) { if ((docFiles.size() <= 0) || ((succFilesCount >= 1) && (succFilesCount >= (int) (docFiles.size() / 2)))) { if (!npwp.getBxDocsJson().equals(npwp.getF1cDocsJson())) { multipart.addFormField("SETDOCS_JSON" + index, "1"); reqBuilder.addPart("SETDOCS_JSON" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETDOCS_JSON" + index, "0"); reqBuilder.addPart("SETDOCS_JSON" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("DOCS_JSON" + index, StringEscapeUtils.escapeJava(npwp.getF1cDocsJson())); reqBuilder.addPart("DOCS_JSON" + index, new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cDocsJson()), ContentType.TEXT_PLAIN)); } else logStr += ("NAME " + npwp.getF1cname() + " - Error docFiles count!!! "); } } } if (npwp.getBxSortOrder() != npwp.getF1cSortOrder()) { multipart.addFormField("SETSORT_ORDER" + index, "1"); reqBuilder.addPart("SETSORT_ORDER" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSORT_ORDER" + index, "0"); reqBuilder.addPart("SETSORT_ORDER" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("SORT_ORDER" + index, "" + npwp.getF1cSortOrder()); reqBuilder.addPart("SORT_ORDER" + index, new StringBody("" + npwp.getF1cSortOrder(), ContentType.TEXT_PLAIN)); if (!npwp.getBxDescription().equals(npwp.getF1cDescription())) { multipart.addFormField("SETDESCRIPTION" + index, "1"); reqBuilder.addPart("SETDESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETDESCRIPTION" + index, "0"); reqBuilder.addPart("SETDESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("DESCRIPTION" + index, StringEscapeUtils.escapeJava(npwp.getF1cDescription())); reqBuilder.addPart("DESCRIPTION" + index, new StringBody("" + npwp.getF1cSortOrder(), ContentType.TEXT_PLAIN)); if (!npwp.getBxFullDescription().equals(npwp.getF1cFullDescription())) { multipart.addFormField("SETFULL_DESCRIPTION" + index, "1"); reqBuilder.addPart("SETFULL_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETFULL_DESCRIPTION" + index, "0"); reqBuilder.addPart("SETFULL_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("FULL_DESCRIPTION" + index, StringEscapeUtils.escapeJava(npwp.getF1cFullDescription())); reqBuilder.addPart("FULL_DESCRIPTION" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cFullDescription()), ContentType.TEXT_PLAIN)); if (!npwp.getBxTypeCompleting().equals(npwp.getF1cTypeCompleting())) { multipart.addFormField("SETTYPE_COMPLETING" + index, "1"); reqBuilder.addPart("SETTYPE_COMPLETING" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETTYPE_COMPLETING" + index, "0"); reqBuilder.addPart("SETTYPE_COMPLETING" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("TYPE_COMPLETING" + index, StringEscapeUtils.escapeJava(npwp.getF1cTypeCompleting())); reqBuilder.addPart("TYPE_COMPLETING" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cTypeCompleting()), ContentType.TEXT_PLAIN)); if (!npwp.getBxCharGabarits().equals(npwp.getF1cCharGabarits())) { multipart.addFormField("SETCHAR_GABARITS" + index, "1"); reqBuilder.addPart("SETCHAR_GABARITS" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETCHAR_GABARITS" + index, "0"); reqBuilder.addPart("SETCHAR_GABARITS" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("CHAR_GABARITS" + index, StringEscapeUtils.escapeJava(npwp.getF1cCharGabarits())); reqBuilder.addPart("CHAR_GABARITS" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cCharGabarits()), ContentType.TEXT_PLAIN)); if (!npwp.getBxShortDescription().equals(npwp.getF1cShortDescription())) { multipart.addFormField("SETSHORT_DESCRIPTION" + index, "1"); reqBuilder.addPart("SETSHORT_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSHORT_DESCRIPTION" + index, "0"); reqBuilder.addPart("SETSHORT_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("SHORT_DESCRIPTION" + index, StringEscapeUtils.escapeJava(npwp.getF1cShortDescription())); reqBuilder.addPart("SHORT_DESCRIPTION" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cShortDescription()), ContentType.TEXT_PLAIN)); if (!npwp.getBxDocumentation().equals(npwp.getF1cDocumentation())) { multipart.addFormField("SETDOCUMENTATION" + index, "1"); reqBuilder.addPart("SETDOCUMENTATION" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETDOCUMENTATION" + index, "0"); reqBuilder.addPart("SETDOCUMENTATION" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("DOCUMENTATION" + index, StringEscapeUtils.escapeJava(npwp.getF1cDocumentation())); reqBuilder.addPart("DOCUMENTATION" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cDocumentation()), ContentType.TEXT_PLAIN)); if (!npwp.getBxVideoDescription().equals(npwp.getF1cVideoDescription())) { multipart.addFormField("SETVIDEO_DESCRIPTION" + index, "1"); reqBuilder.addPart("SETVIDEO_DESCRIPTION" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETVIDEO_DESCRIPTION" + index, "0"); reqBuilder.addPart("SETVIDEO_DESCRIPTION" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("VIDEO_DESCRIPTION" + index, StringEscapeUtils.escapeJava(npwp.getF1cVideoDescription())); reqBuilder.addPart("VIDEO_DESCRIPTION" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cVideoDescription()), ContentType.TEXT_PLAIN)); if (npwp.getBxCollapsevc() != npwp.getF1cCollapsevc()) { multipart.addFormField("SETCOLLAPSEVC" + index, "1"); reqBuilder.addPart("SETCOLLAPSEVC" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETCOLLAPSEVC" + index, "0"); reqBuilder.addPart("SETCOLLAPSEVC" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("COLLAPSEVC" + index, StringEscapeUtils.escapeJava("" + npwp.getF1cCollapsevc())); reqBuilder.addPart("COLLAPSEVC" + index, new StringBody( StringEscapeUtils.escapeJava("" + npwp.getF1cCollapsevc()), ContentType.TEXT_PLAIN)); if (!npwp.getBxAdvants().equals(npwp.getF1cAdvants())) { multipart.addFormField("SETADVANTS" + index, "1"); reqBuilder.addPart("SETADVANTS" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETADVANTS" + index, "0"); reqBuilder.addPart("SETADVANTS" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("ADVANTS" + index, StringEscapeUtils.escapeJava(npwp.getF1cAdvants())); reqBuilder.addPart("ADVANTS" + index, new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cAdvants()), ContentType.TEXT_PLAIN)); if (!npwp.getBxFilterProps().equals(npwp.getF1cFilterProps())) { multipart.addFormField("SETFILTER_PROPS" + index, "1"); reqBuilder.addPart("SETFILTER_PROPS" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETFILTER_PROPS" + index, "0"); reqBuilder.addPart("SETFILTER_PROPS" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("FILTER_PROPS" + index, StringEscapeUtils.escapeJava(npwp.getF1cFilterProps())); reqBuilder.addPart("FILTER_PROPS" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cFilterProps()), ContentType.TEXT_PLAIN)); if (!npwp.getBxSeoAliasUrl().equals(npwp.getF1cSeoAliasUrl()) && npwp.getF1cSeoAliasUrl().length() > 3) { multipart.addFormField("SETSEO_ALIAS_URL" + index, "1"); reqBuilder.addPart("SETSEO_ALIAS_URL" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSEO_ALIAS_URL" + index, "0"); reqBuilder.addPart("SETSEO_ALIAS_URL" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("SEO_ALIAS_URL" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoAliasUrl())); reqBuilder.addPart("SEO_ALIAS_URL" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cSeoAliasUrl()), ContentType.TEXT_PLAIN)); if (npwp.getBxSeoAliasUrl().length() <= 0 && npwp.getF1cSeoAliasUrl().length() <= 3 && npwp.getF1cname().length() > 0) { multipart.addFormField("SETSEO_ALIAS_URL_FROM_NAME" + index, "1"); multipart.addFormField("SEO_ALIAS_URL_FROM_NAME" + index, StringEscapeUtils.escapeJava(npwp.getF1cname())); reqBuilder.addPart("SETSEO_ALIAS_URL_FROM_NAME" + index, new StringBody("1", ContentType.TEXT_PLAIN)); reqBuilder.addPart("SEO_ALIAS_URL_FROM_NAME" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cname()), ContentType.TEXT_PLAIN)); } if (!npwp.getBxSeoTitle().equals(npwp.getF1cSeoTitle())) { multipart.addFormField("SETSEO_TITLE" + index, "1"); reqBuilder.addPart("SETSEO_TITLE" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSEO_TITLE" + index, "0"); reqBuilder.addPart("SETSEO_TITLE" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("SEO_TITLE" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoTitle())); reqBuilder.addPart("SEO_TITLE" + index, new StringBody( StringEscapeUtils.escapeJava(npwp.getF1cSeoTitle()), ContentType.TEXT_PLAIN)); if (!npwp.getBxSeoH1().equals(npwp.getF1cSeoH1())) { multipart.addFormField("SETSEO_H1" + index, "1"); reqBuilder.addPart("SETSEO_H1" + index, new StringBody("1", ContentType.TEXT_PLAIN)); } else { multipart.addFormField("SETSEO_H1" + index, "0"); reqBuilder.addPart("SETSEO_H1" + index, new StringBody("0", ContentType.TEXT_PLAIN)); } multipart.addFormField("SEO_H1" + index, StringEscapeUtils.escapeJava(npwp.getF1cSeoH1())); reqBuilder.addPart("SEO_H1" + index, new StringBody(StringEscapeUtils.escapeJava(npwp.getF1cSeoH1()), ContentType.TEXT_PLAIN)); index++; } try { if (logStr.length() > 0) cbLogsFacade.insertLog("INFO", "UPD SECT TO SEND ", "<p style=\"font-size:10px !important;\">" + logStr + "</p>"); } catch (Exception lgen) { } List<String> response = multipart.finish(); for (String line : response) { sreply = sreply + line; } /*sreply = "{}"; HttpEntity reqEntity = reqBuilder.build(); httppost.setEntity(reqEntity); //System.out.println("executing request " + httppost.getRequestLine()); try { CloseableHttpResponse clresponse = httpclient.execute(httppost); try { //System.out.println("----------------------------------------"); //clresponse.getStatusLine(); HttpEntity resEntity = clresponse.getEntity(); if (resEntity != null) { //System.out.println("Response content length: " + resEntity.getContentLength()); //resEntity.getContent(); resEntity.getContentEncoding() try { String responseString = EntityUtils.toString(resEntity, "UTF-8"); sreply = responseString; EntityUtils.consume(resEntity); } catch(Exception ee) { } } } finally { try { clresponse.close(); } catch(Exception ee) { } } } catch(Exception ee) { }*/ try { JsonReader jsonReader = Json.createReader(new StringReader(sreply)); JsonObject jobject = jsonReader.readObject(); try { cbLogsFacade.insertLog("INFO", "SUCCESS OF PARSE SERVER REPLY", "SUCCESS OF PARSE SERVER REPLY=" + jobject.toString()); } catch (Exception lge) { } try { if (jobject.getString("critical_info", "").length() > 0) cbLogsFacade.insertLog("CRITICAL_INFO", "SERVER REPLY DETAIL", jobject.getString("critical_info", "")); } catch (Exception lge) { } try { if (jobject.getString("critical_errs", "").length() > 0) cbLogsFacade.insertLog("CRITICAL_ERRS", "SERVER REPLY DETAIL", jobject.getString("critical_errs", "")); } catch (Exception lge) { } } catch (Exception pe) { try { cbLogsFacade.insertLog("ERROR", "ERROR OF PARSE SERVER REPLY", "ERROR OF PARSE SERVER REPLY" + sreply); } catch (Exception lge) { } } } catch (Exception ex) { try { cbLogsFacade.insertLog("ERROR", "ERROR of postMultipartSectUpd", logStr + " ERROR of postMultipartSectUpd " + ex); } catch (Exception lge) { } } return reply; }
From source file:org.apache.batchee.tools.maven.DiagramMojo.java
private void saveView(final Dimension currentSize, final Dimension desiredSize, final String name, final VisualizationViewer<Node, Edge> viewer) throws MojoExecutionException { BufferedImage bi = new BufferedImage(currentSize.width, currentSize.height, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = bi.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); final boolean db = viewer.isDoubleBuffered(); viewer.setDoubleBuffered(false);/*from w ww. jav a 2 s. c om*/ viewer.paint(g); viewer.setDoubleBuffered(db); if (!currentSize.equals(desiredSize)) { final double xFactor = desiredSize.width * 1. / currentSize.width; final double yFactor = desiredSize.height * 1. / currentSize.height; final double factor = Math.min(xFactor, yFactor); getLog().info("optimal size is (" + currentSize.width + ", " + currentSize.height + ")"); getLog().info("scaling with a factor of " + factor); final AffineTransform tx = new AffineTransform(); tx.scale(factor, factor); final AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); BufferedImage biNew = new BufferedImage((int) (bi.getWidth() * factor), (int) (bi.getHeight() * factor), bi.getType()); bi = op.filter(bi, biNew); } g.dispose(); OutputStream os = null; try { final File file = new File(output, (outputFileName != null ? outputFileName : name) + "." + format); os = new FileOutputStream(file); if (!ImageIO.write(bi, format, os)) { throw new MojoExecutionException("can't save picture " + name + "." + format); } getLog().info("Saved " + file.getAbsolutePath()); } catch (final IOException e) { throw new MojoExecutionException("can't save the diagram", e); } finally { if (os != null) { try { os.flush(); os.close(); } catch (final IOException e) { // no-op } } } }
From source file:org.apache.batchee.tools.maven.doc.DiagramGenerator.java
private void saveView(final Dimension currentSize, final Dimension desiredSize, final String name, final VisualizationViewer<Node, Edge> viewer) { BufferedImage bi = new BufferedImage(currentSize.width, currentSize.height, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = bi.createGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); final boolean db = viewer.isDoubleBuffered(); viewer.setDoubleBuffered(false);/*from w w w . j a va2 s . co m*/ viewer.paint(g); viewer.setDoubleBuffered(db); if (!currentSize.equals(desiredSize)) { final double xFactor = desiredSize.width * 1. / currentSize.width; final double yFactor = desiredSize.height * 1. / currentSize.height; final double factor = Math.min(xFactor, yFactor); info("optimal size is (" + currentSize.width + ", " + currentSize.height + ")"); info("scaling with a factor of " + factor); final AffineTransform tx = new AffineTransform(); tx.scale(factor, factor); final AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR); BufferedImage biNew = new BufferedImage((int) (bi.getWidth() * factor), (int) (bi.getHeight() * factor), bi.getType()); bi = op.filter(bi, biNew); } g.dispose(); OutputStream os = null; try { final File file = new File(output, (outputFileName != null ? outputFileName : name) + "." + format); os = new FileOutputStream(file); if (!ImageIO.write(bi, format, os)) { throw new IllegalStateException("can't save picture " + name + "." + format); } info("Saved " + file.getAbsolutePath()); } catch (final IOException e) { throw new IllegalStateException("can't save the diagram", e); } finally { if (os != null) { try { os.flush(); os.close(); } catch (final IOException e) { // no-op } } } }
From source file:org.asqatasun.sebuilder.interpreter.TgTestRun.java
/** * Resize the snapshot image to 270*170/*from w w w . j ava2s. c o m*/ * * @param originalImage * @return */ private BufferedImage resizeImage(BufferedImage originalImage) { float scaleRatio = (float) 270 / originalImage.getWidth(); int resizedImageHeight = Float.valueOf(originalImage.getHeight() * scaleRatio).intValue(); BufferedImage resizedImage = new BufferedImage(270, resizedImageHeight, originalImage.getType()); Graphics2D g = resizedImage.createGraphics(); g.drawImage(originalImage, 0, 0, 270, resizedImageHeight, null); g.dispose(); return resizedImage.getSubimage(0, 0, 270, 170); }
From source file:org.codice.alliance.imaging.chip.transformer.CatalogOutputAdapter.java
private void setImageDataFields(BufferedImage chip, ImageSegment chipImageSegment) throws IOException { int[] componentSizes = chip.getColorModel().getComponentSize(); int pixelSize = chip.getColorModel().getPixelSize(); switch (chip.getType()) { case BufferedImage.TYPE_BYTE_GRAY: case BufferedImage.TYPE_USHORT_GRAY: case BufferedImage.TYPE_BYTE_BINARY: setMonochrome(chipImageSegment, componentSizes[0], pixelSize); break;//from w ww.ja v a2 s . c o m case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_INT_BGR: setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR, componentSizes[0], pixelSize / 3, new String[] { "B", "G", "R" }); break; case BufferedImage.TYPE_4BYTE_ABGR: case BufferedImage.TYPE_4BYTE_ABGR_PRE: setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBTRUECOLOUR, componentSizes[0], pixelSize / 4, new String[] { "B", "G", "R" }); break; case BufferedImage.TYPE_INT_ARGB_PRE: case BufferedImage.TYPE_INT_ARGB: setARGB(chipImageSegment, componentSizes[0], pixelSize); break; case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_USHORT_555_RGB: setRGB(chipImageSegment, componentSizes[0], pixelSize); break; case BufferedImage.TYPE_CUSTOM: if (componentSizes.length == 1) { setMonochrome(chipImageSegment, componentSizes[0], pixelSize); } else if (componentSizes.length == 3) { setRGB(chipImageSegment, componentSizes[0], pixelSize); } else if (componentSizes.length == 4) { setARGB(chipImageSegment, componentSizes[0], pixelSize); } else { throw new IOException( "unsupported color model for image type CUSTOM, only monochrome and 32-bit argb are supported"); } break; case BufferedImage.TYPE_BYTE_INDEXED: setImageFieldHelper(chipImageSegment, PixelValueType.INTEGER, ImageRepresentation.RGBLUT, componentSizes[0], pixelSize, new String[] { "LU" }); break; case BufferedImage.TYPE_USHORT_565_RGB: // don't know how to handle this one, since the bitsPerPixelPerBand is not consistent break; default: throw new IOException("unsupported image data type: type=" + chip.getType()); } }