def showImgWithLegend(width=None, height=None): """ This function shows the image and legend from current IDV window while in GUI mode. Optional arguments are width and height in pixels, they currently default to 600 and 400""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize, toBufferedImage import java import java.awt.Robot as Robot import java.awt.Rectangle as Rectangle import java.awt.Toolkit as Toolkit from ucar.unidata.util import Misc VM = idv.getViewManager() VMC = VM.getContents() VMCC = VMC.getComponent( 1 ) # the view and legend ; 0 is left most part of view window with controls for perspective views siz = VMCC.getSize() loc = VMCC.getLocationOnScreen() gc = VMCC.getGraphicsConfiguration() loc.x -= gc.getBounds().x loc.y -= gc.getBounds().y robotx = Robot(gc.getDevice()) VM.toFront() Misc.sleep(250) img = robotx.createScreenCapture( Rectangle(loc.x, loc.y, siz.width, siz.height)) if width != None and height != None: img = toBufferedImage(resize(img, width, height)) bos = ByteArrayOutputStream() ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)) data = bos.toString("UTF-8") return {"display": "image", "data": data}
def save_mediafiles_into_catroid_directory_structure(): def update_md5_hash(current_md5_name, file_path_for_update): resource_maps = list(sb2_project.project_code.resource_dicts_of_md5_name(current_md5_name)) md5_name = common.md5_hash(file_path_for_update) + os.path.splitext(file_path_for_update)[1] for resource_map in resource_maps: if sb2keys.COSTUME_MD5 in resource_map: resource_map[sb2keys.COSTUME_MD5] = md5_name elif sb2keys.SOUND_MD5 in resource_map: resource_map[sb2keys.SOUND_MD5] = md5_name else: assert False, "Unknown dict: {}".resource_map return md5_name for md5_name, src_path in sb2_project.md5_to_resource_path_map.iteritems(): file_ext = os.path.splitext(md5_name)[1].lower() converted_file = False # TODO; extract method if file_ext in {".png", ".svg", ".jpg", ".gif"}: target_dir = images_path # # WORKAROUNF: penLayerMD5 file # if not resource_maps: # continue if file_ext == ".svg": # converting svg to png -> new md5 and filename src_path = svgtopng.convert(src_path) converted_file = True elif md5_name in sb2_project.background_md5_names: # resize background if not matching the default resolution imageFile = File(src_path) pngImage = ImageIO.read(imageFile) if pngImage.getWidth() > sb2.STAGE_WIDTH_IN_PIXELS or pngImage.getHeight() > sb2.STAGE_HEIGHT_IN_PIXELS: resizedImage = imageresizer.resize_png(pngImage, sb2.STAGE_WIDTH_IN_PIXELS, sb2.STAGE_HEIGHT_IN_PIXELS) # FIXME src_path = src_path.replace(".png", "resized.png") ImageIO.write(resizedImage, "png", File(src_path)) converted_file = True elif file_ext in {".wav", ".mp3"}: target_dir = sounds_path if file_ext == ".wav": if not wavconverter.is_android_compatible_wav(src_path): temp_path = src_path.replace(".wav", "converted.wav") wavconverter.convert_to_android_compatible_wav(src_path, temp_path) src_path = temp_path converted_file = True else: assert file_ext in {".json"}, md5_name continue assert os.path.exists(src_path), "Not existing: {}".format(src_path) if converted_file: md5_name = update_md5_hash(md5_name, src_path) # if file is used multiple times: single md5, multiple filenames for catroid_file_name in _convert_resource_name(sb2_project, md5_name): shutil.copyfile(src_path, os.path.join(target_dir, catroid_file_name)) if converted_file: os.remove(src_path)
def showImgWithFullWindow(width=None, height=None): """ This function shows the image from current IDV window while in GUI mode. optional arguments are width and height in pixels, they currently default to 600 and 400""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize, toBufferedImage import java import java.awt.Robot as Robot import java.awt.Rectangle as Rectangle import java.awt.Toolkit as Toolkit from ucar.unidata.util import Misc VM = idv.getViewManager() myframe = VM.getDisplayWindow().getComponent() robotx = Robot(myframe.getGraphicsConfiguration().getDevice()) VM.toFront() #robotx.delay(250) Misc.sleep(350) pause() img = robotx.createScreenCapture( Rectangle(myframe.getX(), myframe.getY(), myframe.getWidth(), myframe.getHeight())) if width != None and height != None: img = toBufferedImage(resize(img, width, height)) bos = ByteArrayOutputStream() ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)) data = bos.toString("UTF-8") return {"display": "image", "data": data}
def showImgWithFullWindow(width=None,height=None): """ This function shows the image from current IDV window while in GUI mode. optional arguments are width and height in pixels, they currently default to 600 and 400""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize,toBufferedImage import java import java.awt.Robot as Robot import java.awt.Rectangle as Rectangle import java.awt.Toolkit as Toolkit from ucar.unidata.util import Misc VM=idv.getViewManager() myframe=VM.getDisplayWindow().getComponent() robotx = Robot(myframe.getGraphicsConfiguration().getDevice()) VM.toFront(); #robotx.delay(250) Misc.sleep(350) pause() img=robotx.createScreenCapture(Rectangle( myframe.getX(),myframe.getY(),myframe.getWidth(),myframe.getHeight())) if width != None and height != None: img=toBufferedImage(resize(img,width,height)); bos=ByteArrayOutputStream(); ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)); data = bos.toString("UTF-8"); return {"display":"image","data":data}
def image_byte_array(self): baos = ByteArrayOutputStream() ImageIO.write(self.image(), "png", baos) baos.flush() image_bytes = baos.toByteArray() baos.close() return image_bytes
def image_byte_array(self): baos = ByteArrayOutputStream(); ImageIO.write( self.image(), "png", baos ); baos.flush(); image_bytes = baos.toByteArray(); baos.close() return image_bytes
def saveImageFile(self, fileName, width=None, height=None, rawData=None): if width == None: width = self.width if height == None: height = self.height if rawData == None: rawData = self.rawData # Rend an image # Create a buffered image in which to draw # bufferedImage = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); # bufferedImage.setRGB(0, 0, width, height, rawData, 0, width); bufferedImage = BufferedImage(width, height, BufferedImage.TYPE_BYTE_INDEXED) # bufferedImage = BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); bufferedImage.getRaster().setDataElements(0, 0, width, height, rawData) # Create a graphics contents on the buffered image, draw something and then dispose it # g2d = bufferedImage.createGraphics(); # g2d.setColor(Color.white); # g2d.fillRect(0, 0, width, height); # g2d.setColor(Color.black); # g2d.fillOval(0, 0, width, height); # g2d.dispose(); # Save as PNG file = File(fileName) ImageIO.write(bufferedImage, "png", file) return
def render_shape_to_graphics(self, shape): r = shape.getShapeRenderer() # Find the size that the shape will be rendered to at the specified scale and resolution. shapeSizeInPixels = r.getSizeInPixels(1.0, 96.0) # Rotating the shape may result in clipping as the image canvas is too small. Find the longest side # and make sure that the graphics canvas is large enough to compensate for this. maxSide = Math.max(shapeSizeInPixels.width, shapeSizeInPixels.height) image = BufferedImage(int(maxSide * 1.25), int(maxSide * 1.25), BufferedImage.TYPE_INT_ARGB) # Rendering to a graphics object means we can specify settings and transformations to be applied to # the shape that is rendered. In our case we will rotate the rendered shape. gr = image.getGraphics() # Clear the shape with the background color of the document. gr.setBackground(shape.getDocument().getPageColor()) gr.clearRect(0, 0, image.getWidth(), image.getHeight()) # Center the rotation using translation method below gr.translate(image.getWidth() / 8, image.getHeight() / 2) # Rotate the image by 45 degrees. gr.rotate(45 * Math.PI / 180) # Undo the translation. gr.translate(-image.getWidth() / 8, -image.getHeight() / 2) # Render the shape onto the graphics object. r.renderToSize(gr, 0, 0, shapeSizeInPixels.width, shapeSizeInPixels.height) ImageIO.write(image, "png", File(self.dataDir + "TestFile.RenderToGraphics.png")) gr.dispose() print "Shape rendered to Graphics successfully."
def showImgWithLegend(width=None,height=None): """ This function shows the image and legend from current IDV window while in GUI mode. Optional arguments are width and height in pixels, they currently default to 600 and 400""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize,toBufferedImage import java import java.awt.Robot as Robot import java.awt.Rectangle as Rectangle import java.awt.Toolkit as Toolkit from ucar.unidata.util import Misc VM=idv.getViewManager() VMC=VM.getContents() VMCC=VMC.getComponent(1) # the view and legend ; 0 is left most part of view window with controls for perspective views siz=VMCC.getSize() loc= VMCC.getLocationOnScreen() gc= VMCC.getGraphicsConfiguration() loc.x -= gc.getBounds().x loc.y -= gc.getBounds().y robotx=Robot(gc.getDevice()) VM.toFront() Misc.sleep(250) img = robotx.createScreenCapture(Rectangle(loc.x, loc.y,siz.width, siz.height)) if width != None and height != None: img=toBufferedImage(resize(img,width,height)); bos=ByteArrayOutputStream(); ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)); data = bos.toString("UTF-8"); return {"display":"image","data":data}
def save_editable_image_as_png_to_disk(editable_image, path, overwrite=False): assert isinstance( editable_image, BufferedImage), "No *editable* image (instance of ImageIO) given!" assert overwrite == True or os.path.isfile( path) == False, "File already exists" ImageIO.write(editable_image, "png", File(path))
def _screenshot(name): name = name.replace("<","-").replace(">","-").replace(":","-").replace("|","-").replace("*","-").replace("\"","-").replace("/","-").replace("\\","-") from java.awt import Toolkit,Robot,Rectangle from javax.imageio import ImageIO from java.io import File screenRect = Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) capture = Robot().createScreenCapture(screenRect) ImageIO.write(capture, "png", File(_UXTST_OUTPUT_PATH_ + name+".png"))
def BufferedImgToNotebook(img): from java.io import ByteArrayOutputStream from java.util import Base64 ##only in java8 from javax.imageio import ImageIO bos=ByteArrayOutputStream(); ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)); data = bos.toString("UTF-8"); return {"display":"image","data":data}
def jpg2bmp(src): # load jpg b = bmp_name(src) f = File(src) image = ImageIO.read(f) output = File(b) ImageIO.write(image,"bmp",output)
def convert(input_svg_path, rotation_x, rotation_y, ns_registry_lock): assert isinstance(input_svg_path, (str, unicode)) assert os.path.splitext(input_svg_path)[1] == ".svg" input_file_name = os.path.splitext(input_svg_path)[0] output_png_path = "{}_rotX_{}_rotY_{}.png".format(input_file_name, rotation_x, rotation_y) _log.info(" converting '%s' to Pocket Code compatible png '%s'", input_svg_path, output_png_path) output_svg_path = input_svg_path.replace(".svg", "_modified.svg") output_svg_URI = Paths.get(output_svg_path).toUri().toURL().toString() if os.path.exists(output_png_path): _log.error(" '%s' already exists", output_png_path) #assert False # "Still a Duplicate?" # remove temporary files if os.path.exists(output_svg_path): os.remove(output_svg_path) return output_png_path # avoid duplicate conversions! png_ostream = None error = None try: _parse_and_rewrite_svg_file(input_svg_path, output_svg_path, ns_registry_lock) command = "svg2png" out = subprocess.check_output([command, output_svg_path, "-o", output_png_path]) _log.info(" converting '%s' to Pocket Code compatible png '%s'", input_svg_path, output_png_path) assert os.path.exists(output_png_path) final_image = _translation(output_png_path, rotation_x, rotation_y) if final_image is None: raise RuntimeError("...") from javax.imageio import ImageIO from java.io import File ImageIO.write(final_image, "PNG", File(output_png_path)) return output_png_path except BaseException as err: import traceback import sys exc_info = sys.exc_info() _log.error(err) _log.error(traceback.format_exc()) _log.error(exc_info) error = common.ScratchtobatError("SVG to PNG conversion call failed for: %s" % input_svg_path) finally: # free resources if png_ostream != None: png_ostream.flush() png_ostream.close() # remove temporary files if os.path.exists(output_svg_path): os.remove(output_svg_path) if error != None: raise error
def BufferedImgToNotebook(img): from java.io import ByteArrayOutputStream from java.util import Base64 ##only in java8 from javax.imageio import ImageIO bos = ByteArrayOutputStream() ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)) data = bos.toString("UTF-8") return {"display": "image", "data": data}
def __output_image(self, f): out = io.FileOutputStream(f) size = self.preferredSize im = image.BufferedImage(size.width, size.height, image.BufferedImage.TYPE_INT_RGB) g2d = im.getGraphics() self.paint(g2d) ImageIO.write(im,'png',out) out.close() gui_status_bar.show_message("Image saved.")
def convertPNG(self, isStageCostume, costume_info, costume_src_path, costume_dest_path): import java.io.File new_image = svgtopng._translation(costume_src_path, costume_info["rotationCenterX"], costume_info["rotationCenterY"]) ImageIO.write(new_image, "png", java.io.File(costume_dest_path)) if JsonKeys.COSTUME_RESOLUTION in costume_info: self.resize_png(costume_dest_path, costume_dest_path, costume_info[JsonKeys.COSTUME_RESOLUTION])
def outputImage(self, bufferedImage, filename): if not filename.endswith(SUPPORTED_FORMATS): filename += SUPPORTED_FORMATS[0] imageType = filename[-3:] from java.io import ByteArrayOutputStream, File from javax.imageio import ImageIO bytes = ByteArrayOutputStream() ImageIO.write(bufferedImage, imageType, bytes) f = File(filename) from com.raytheon.uf.common.util import FileUtil FileUtil.bytes2File(bytes.toByteArray(), f)
def updateProduct(self, *args): try: value = self.lstProducts.getSelectedValue() except: return if value == None: return #try: if True: width = 150 height = 150 #gvSIGPath = Utilities.TEMPDIRECTORYPATH gvSIGPath = "/home/osc/temp" outputPath = os.path.join( gvSIGPath, value.getName() + "_%sx%s.jpg" % (width, height)) #Utilities.TEMPDIRECTORYPATH if os.path.exists(outputPath) == False: url = value.getPreviewLink() f = download(url) total_size = int(f.headers["Content-Length"]) MB_size = round(total_size / 1048576, 2) block_size = 1024 * 1024 outputPathFull = gvSIGPath + value.getName() + ".jpg" with open(outputPath, "wb") as file: while True: block = f.read(block_size) dSize = round( int(os.stat(outputPath).st_size) / 1048576, 2) print "(" + str(dSize) + "/" + str( MB_size) + " MB) " + url + "Downloading" if not block: break file.write(block) img = ImageIO.read(outputPathFull) tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH) resized = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) g2d = resized.createGraphics() g2d.drawImage(tmp, 0, 0, None) g2d.dispose() ImageIO.write(resized, "jpg", outputPath) else: print "already downloaded" myPicture = ImageIcon(ImageIO.read(File(outputPath))) self.txtInfo.setText(value.getInfoString()) self.tabInfo.updateUI() self.lstProducts.updateUI() self.lstProducts.revalidate() self.lstProducts.repaint() #except: # myPicture = ImageIcon() self.lblPreview.setIcon(myPicture)
def saveToPNG(p,filename): from java.awt.image import BufferedImage from javax.imageio import ImageIO from java.io import File bi = BufferedImage(p.size.width, p.size.height, BufferedImage.TYPE_INT_ARGB) g = bi.createGraphics() p.invalidate() p.validate() p.paint(g) g.dispose(); ImageIO.write(bi,"png", File(filename));
def saveToPNG(p, filename): from java.awt.image import BufferedImage from javax.imageio import ImageIO from java.io import File bi = BufferedImage(p.size.width, p.size.height, BufferedImage.TYPE_INT_ARGB) g = bi.createGraphics() p.invalidate() p.validate() p.paint(g) g.dispose() ImageIO.write(bi, "png", File(filename))
def enlargeimage(self,image,imagewidth,imageheight): imageFile = open(image); ###j make image bigger for easier reading i = ImageIO.read(imageFile) largeimage = i.getScaledInstance(imagewidth, imageheight, awt.Image.SCALE_SMOOTH) bImage = awt.image.BufferedImage(largeimage.getWidth(),largeimage.getHeight(),awt.image.BufferedImage.TYPE_INT_ARGB) g = bImage.createGraphics() g.drawImage(largeimage,0,0,None) g.dispose() outputfile = File(image) ImageIO.write(bImage, "png", outputfile) return re.sub("[^a-zA-Z0-9\.\- ]","", Image.text(image))
def showImg(width=400,height=300): """ This function shows the image from current IDV frame, optional arguments are width and height in pixels, they currently default to 400 and 300""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize,toBufferedImage pause() img=getImage() img=toBufferedImage(resize(img,width,height)); bos=ByteArrayOutputStream(); ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)); data = bos.toString("UTF-8"); return {"display":"image","data":data}
def save_as_png(p,filename): """ saves plot window (G2Dialog) created by newPlot(title) method as a png graphics file """ from java.awt.image import BufferedImage from javax.imageio import ImageIO from java.io import File bi = BufferedImage(p.size.width, p.size.height, BufferedImage.TYPE_INT_ARGB) g = bi.createGraphics() p.invalidate() p.validate() p.paint(g) g.dispose(); ImageIO.write(bi,"png", File(filename));
def main(self, args): width = 400; height = 400; im = BufferedImage(width,height,BufferedImage.TYPE_BYTE_BINARY); raster = im.getRaster(); for h in range(height): for w in range(width): if (h / 50 + w / 50) % 2 == 0: raster.setSample(w,h,0,0); else: raster.setSample(w,h,0,1); try: ImageIO.write(im,"PNG", File("checkboard.png")); except IOException: print "can not open the file"
def save_screenshot_to(self, path): """Saves a screenshot to the specified file. The directory holding the file must exist or an exception is raised. """ path = os.path.abspath(path.replace('/', os.sep)) if not os.path.exists(os.path.dirname(path)): raise RuntimeError("Directory '%s' where to save the screenshot does " "not exist" % os.path.dirname(path)) screensize = Toolkit.getDefaultToolkit().getScreenSize() rectangle = Rectangle(0, 0, screensize.width, screensize.height) image = Robot().createScreenCapture(rectangle) ImageIO.write(image, "jpg", File(path)) print "Screenshot saved to '%s'" % path return path
def save_as_png(p, filename): """ saves plot window (G2Dialog) created by newPlot(title) method as a png graphics file """ from java.awt.image import BufferedImage from javax.imageio import ImageIO from java.io import File bi = BufferedImage(p.size.width, p.size.height, BufferedImage.TYPE_INT_ARGB) g = bi.createGraphics() p.invalidate() p.validate() p.paint(g) g.dispose() ImageIO.write(bi, "png", File(filename))
def save_screenshot_to(self, path): """Saves a screenshot to the specified file. The directory holding the file must exist or an exception is raised. """ path = os.path.abspath(path.replace('/', os.sep)) if not os.path.exists(os.path.dirname(path)): raise RuntimeError( "Directory '%s' where to save the screenshot does " "not exist" % os.path.dirname(path)) screensize = Toolkit.getDefaultToolkit().getScreenSize() rectangle = Rectangle(0, 0, screensize.width, screensize.height) image = Robot().createScreenCapture(rectangle) ImageIO.write(image, "jpg", File(path)) print "Screenshot saved to '%s'" % path return path
def _encode(self, img, g, size, **opts): file = opts['file'] if opts.has_key('file') else None if file: # write out to file ImageIO.write(img, self.format, util.toFile(file)) else: # write to byte array out = ByteArrayOutputStream() ImageIO.write(img, self.format, out) bytes = out.toByteArray() # check for strencode flag to check whether to return result as raw # bytes or as string if opts.has_key('strencode'): return str(String(bytes, 0, 0, len(bytes))) return out.toByteArray()
def showImg(width=None,height=None): """ This function shows the image from current IDV frame, optional arguments are width and height in pixels, they currently default to 400 and 300""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize,toBufferedImage pause() #imgx=getImage() currently not working with new changes to idv img=idv.getViewManager().getMaster().getImage(True) if width != None and height != None: img=toBufferedImage(resize(img,width,height)); bos=ByteArrayOutputStream(); ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)); data = bos.toString("UTF-8"); return {"display":"image","data":data}
def showImg(width=None, height=None): """ This function shows the image from current IDV frame, optional arguments are width and height in pixels, they currently default to 400 and 300""" from java.util import Base64 ##only in java8 from javax.imageio import ImageIO from java.io import ByteArrayOutputStream from ucar.unidata.ui.ImageUtils import resize, toBufferedImage pause() #imgx=getImage() currently not working with new changes to idv img = idv.getViewManager().getMaster().getImage(True) if width != None and height != None: img = toBufferedImage(resize(img, width, height)) bos = ByteArrayOutputStream() ImageIO.write(img, "png", Base64.getEncoder().wrap(bos)) data = bos.toString("UTF-8") return {"display": "image", "data": data}
def addSS(self,event): clipboard = Toolkit.getDefaultToolkit().getSystemClipboard() try: image = clipboard.getData(DataFlavor.imageFlavor) except: self.popup("Clipboard not contains image") return vulnPath = self.projPath.getText() + "/" + self.clearStr(self.vulnName.getText()) if not os.path.exists(vulnPath): os.makedirs(vulnPath) name = self.clearStr(self.vulnName.getText()) + str(random.randint(1, 99999))+".jpg" fileName = self.projPath.getText()+"/"+ self.clearStr(self.vulnName.getText()) + "/" + name file = File(fileName) bufferedImage = BufferedImage(image.getWidth(None), image.getHeight(None), BufferedImage.TYPE_INT_RGB); g = bufferedImage.createGraphics(); g.drawImage(image, 0, 0, bufferedImage.getWidth(), bufferedImage.getHeight(), Color.WHITE, None); ImageIO.write(bufferedImage, "jpg", file) self.addVuln(self) self.ssList.setSelectedValue(name,True)
def write(self, filename): """Saves the pixels to a file (.png or .jpg).""" # JEM working directory fix (see above) filename = fixWorkingDirForJEM(filename) # does nothing if not in JEM # *** #print "fixWorkingDirForJEM( filename ) =", filename # get suffix suffix = filename[-3:] suffix = suffix.lower() if suffix == "jpg" or suffix == "png": ImageIO.write(self.image, suffix, File(filename)) # save, and also self.filename = filename # update image filename self.display.setTitle(self.filename) # update display title else: print "Filename must end in .jpg or .png"
def write(self, filename): """Saves the pixels to a file (.png or .jpg).""" # JEM working directory fix (see above) filename = fixWorkingDirForJEM( filename ) # does nothing if not in JEM # *** #print "fixWorkingDirForJEM( filename ) =", filename # get suffix suffix = filename[-3:] suffix = suffix.lower() if suffix == "jpg" or suffix =="png": ImageIO.write(self.image, suffix, File(filename)) # save, and also self.filename = filename # update image filename self.display.setTitle(self.filename) # update display title else: print "Filename must end in .jpg or .png"
def resize_png(self, path_in, path_out, bitmapResolution): import java.awt.image.BufferedImage import java.io.File import java.io.IOException input = java.io.File(path_in) image = ImageIO.read(input) from math import ceil new_height = int(ceil(image.getHeight() / float(bitmapResolution))) new_height = new_height if new_height > 2 else 2 new_width = int(ceil(image.getWidth() / float(bitmapResolution))) new_width = new_width if new_width > 2 else 2 def resize(img, height, width): tmp = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH) resized = java.awt.image.BufferedImage( width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB) g2d = resized.createGraphics() g2d.drawImage(tmp, 0, 0, None) g2d.dispose() empty = True for x in range(new_width): for y in range(new_height): alpha = (resized.getRGB(x, y) >> 24) & 0xff if alpha > 0: empty = False break if not empty: break if empty: argb = (80 << 24) | (0x00FF00) resized.setRGB(0, 0, argb) resized.setRGB(0, 1, argb) resized.setRGB(1, 1, argb) resized.setRGB(1, 0, argb) return resized resized = resize(image, new_height, new_width) output = java.io.File(path_out) ImageIO.write(resized, "png", output) return path_out
def resize_png(self, path_in, path_out, bitmapResolution): import java.awt.image.BufferedImage import java.io.File import java.io.IOException input = java.io.File(path_in) image = ImageIO.read(input) from math import ceil new_height = int(ceil(image.getHeight() / float(bitmapResolution))) new_height = new_height if new_height > 2 else 2 new_width = int(ceil(image.getWidth() / float(bitmapResolution))) new_width = new_width if new_width > 2 else 2 def resize(img, height, width): tmp = img.getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH) resized = java.awt.image.BufferedImage(width, height, java.awt.image.BufferedImage.TYPE_INT_ARGB) g2d = resized.createGraphics() g2d.drawImage(tmp, 0, 0, None) g2d.dispose() empty = True for x in range(new_width): for y in range(new_height): alpha = (resized.getRGB(x,y) >> 24) & 0xff if alpha > 0: empty = False break if not empty: break if empty: argb = (80 << 24) | (0x00FF00) resized.setRGB(0,0,argb) resized.setRGB(0,1,argb) resized.setRGB(1,1,argb) resized.setRGB(1,0,argb) return resized resized = resize(image, new_height, new_width) output = java.io.File(path_out) ImageIO.write(resized, "png", output) return path_out
graphics.drawString("Generated", 10, graphTopGenerated + 10) graphics.drawString("Used", 10, graphTopUsed + 10) graphics.drawString("Displaced", 10, graphTopDisplaced + 10) graphics.setFont(smallFont) graphics.drawString( "Poor data is denoted by a grey background and black " "foreground.", 30, ((maxHeight + 22) * 5) + 50 + minUsed + minDisplaced + minParasitic) graphics.setFont(keyFont) paint_legend(exported_supplies, graphTopExported) paint_legend(imported_supplies, graphTopImported) paint_legend(generated_supplies, graphTopGenerated) else: image = BufferedImage(400, 400, BufferedImage.TYPE_4BYTE_ABGR) graphics = image.createGraphics() graphics.setColor(Color.BLACK) graphics.drawString("No data available for this period.", 30, 10) os = inv.getResponse().getOutputStream() graphics.setColor(Color.BLACK) ImageIO.write(image, "png", os) os.close() finally: if sess is not None: sess.close() else: from flask import Response inv.response = Response("Stub", status=200)
private static void createQRImage(File qrFile, String qrCodeText, int size, String fileType) throws WriterException, IOException { // Create the ByteMatrix for the QR-Code that encodes the given String Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText, BarcodeFormat.QR_CODE, size, size, hintMap); // Make the BufferedImage that are to hold the QRCode int matrixWidth = byteMatrix.getWidth(); BufferedImage image = new BufferedImage(matrixWidth, matrixWidth, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, matrixWidth, matrixWidth); // Paint and save the image using the ByteMatrix graphics.setColor(Color.BLACK); for (int i = 0; i < matrixWidth; i++) { for (int j = 0; j < matrixWidth; j++) { if (byteMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } ImageIO.write(image, fileType, qrFile); } }
def processExportImage(featureSet, field, formatName, outparams, taskStatus=None): if not formatName in ["PNG", "JPEG", "GIF"]: logger("Not valid format for export images", LOGGER_ERROR) return sm = ToolsSwingLocator.getToolsSwingManager() si = sm.createSimpleImage() if taskStatus != None: taskStatus.setRangeOfValues(0, featureSet.getSize()) if isinstance(field, FeatureAttributeDescriptor): field = field.getName() try: ooption = outparams["option"] oparams = outparams["params"] n = 0 if ooption == 1: for f in featureSet: if taskStatus != None: n += 1 taskStatus.setCurValue(n) if taskStatus.isCancellationRequested(): return value = f.get(field) if value == None or value == "": continue si.set(value) im = si.getBufferedImage() if im == None: logger( "Not able to get Bufferded Image from field " + str(field) + " value:" + str(value), LOGGER_ERROR) continue # Save image ofield = oparams["field"] if isinstance(ofield, FeatureAttributeDescriptor): ofield = ofield.getName() output = f.get(ofield) ImageIO.write(im, formatName, output) elif ooption == 2: for f in featureSet: if taskStatus != None: n += 1 taskStatus.setCurValue(n) if taskStatus.isCancellationRequested(): return value = f.get(field) if value == None or value == "": continue si.set(value) im = si.getBufferedImage() if im == None: logger( "Not able to get Bufferded Image from field " + str(field) + " value:" + str(value), LOGGER_ERROR) continue ofield = oparams["field"] if isinstance(ofield, FeatureAttributeDescriptor): ofield = ofield.getName() oname = f.get(ofield) if oname == None or oname == "": continue outputPath = oparams["path"].getAbsolutePath() output = getUniqueValueFileByField(oname, outputPath, formatName) ImageIO.write(im, formatName, output) elif ooption == 3: s = ExpressionEvaluatorLocator.getManager().createSymbolTable() fst = DALLocator.getDataManager().createFeatureSymbolTable() s.addSymbolTable(fst) exp = oparams["expression"] if exp.isEmpty(): logger("Expression is empty", LOGGER_ERROR) return for f in featureSet: if taskStatus != None: n += 1 taskStatus.setCurValue(n) if taskStatus.isCancellationRequested(): return value = f.get(field) if value == None or value == "": continue si.set(value) im = si.getBufferedImage() fst.setFeature(f) output = exp.execute(s) outputex = output + "." + formatName.lower() if os.path.exists(outputex): logger("Already exists: " + outputex, LOGGER_ERROR) continue ImageIO.write(im, formatName, File(outputex)) except: ex = str(sys.exc_info()[1]) logger( "Not able to export: " + ex + " caused on: " + ex.__class__.__name__, LOGGER_ERROR) try: DisposeUtils.disposeQuietly(featureSet) except: logger("Not able dispose export images feature set", LOGGER_ERROR)
def renderMap(self, connection_parameters=None, sql=None, geom_id_entity=None, geom_entity=None, data_entity=None, map_parameters={}): # Put connection parameters into a java HashMap. params_hashmap = HashMap() for param, value in connection_parameters.items(): if value: params_hashmap.put(param, value) # Get data store. data_store = DataStoreFinder.getDataStore(params_hashmap) # Create VirtualTable from sql. vtable = VirtualTable("vtable", sql) # Set primary key. vtable.setPrimaryKeyColumns([geom_id_entity['ID']]) # metadatata = intententional typo. GT needs to fix the name. vtable.addGeometryMetadatata(geom_entity['ID'], JPolygon, 4326) # Create feature source from virtual table. data_store.addVirtualTable(vtable) feature_source = data_store.getFeatureSource("vtable") # Add styling classes if there was a value entity. if data_entity: # Generate class bounds. num_classes = data_entity.get('num_classes', 25) vmin = float(data_entity.get('min', 0)) vmax = float(data_entity.get('max', 1)) vrange = vmax - vmin class_width = vrange/num_classes classes = [(None, vmin)] for i in range(num_classes): classes.append((vmin + i * class_width, vmin + (i + 1) * class_width)) classes.append((vmax, None)) # Generate style rules for classes. rules = [] for c in classes: rule = self.create_rule(c[0], c[1], vmin, vrange, attr=data_entity['ID']) rules.append(rule) feature_type_style = self.style_factory.createFeatureTypeStyle(rules) style = self.style_factory.createStyle() style.featureTypeStyles().add(feature_type_style) else: style = None # Setup map. gt_map = DefaultMapContext() gt_map.addLayer(feature_source, style) gt_renderer = StreamingRenderer() gt_renderer.setMapContent(gt_map) image_bounds = Rectangle(0, 0, map_parameters.get('WIDTH', 100), map_parameters.get('HEIGHT', 100)) # Set image type based on format. image_format = map_parameters.get('FORMAT', 'image/png') if image_format == 'image/jpeg': image_type = BufferedImage.TYPE_INT_RGB else: image_type = BufferedImage.TYPE_INT_ARGB buffered_image = BufferedImage(image_bounds.width, image_bounds.height, image_type) graphics = buffered_image.createGraphics() # Set background color if not transparent. if not map_parameters.get('TRANSPARENT'): graphics.setPaint(Color.WHITE) graphics.fill(image_bounds) crs = CRS.decode(map_parameters.get('SRS', "EPSG:4326")) bbox = map_parameters.get('BBOX', '-180,-90,180,90') coords = [float(coord) for coord in bbox.split(",")] map_bounds = ReferencedEnvelope(coords[0], coords[2], coords[1], coords[3], crs) gt_renderer.paint(graphics, image_bounds, map_bounds) # Release the JDBC connection and map content. data_store.dispose() gt_renderer.getMapContent().dispose() # Return raw image. byte_array_output_stream = ByteArrayOutputStream() informal_format = re.match('image/(.*)', image_format).group(1) ImageIO.write(buffered_image, informal_format, byte_array_output_stream) byte_array = byte_array_output_stream.toByteArray() raw_image = Py.newString(StringUtil.fromBytes(byte_array)) return raw_image
def _java_screenshot(self, path): size = Toolkit.getDefaultToolkit().getScreenSize() rectangle = Rectangle(0, 0, size.width, size.height) image = Robot().createScreenCapture(rectangle) ImageIO.write(image, 'jpg', File(path))
def base(det, e0, withPoisson, nTraj, dose, sf, bf, name, buildSample, buildParams, xtraParams): """base(det, e0, withPoisson, nTraj, dose, sf, bf, name, buildSample, buildParams) represents \ a generic mechanism for Monte Carlo simulation of x-ray spectra. The argument buildSample \ is a method buildSample(monte,origin,buildParams) taking an instance of MonteCarloSS, the \ position of the origin and a dictionary of build parameters. This method should construct \ the sample geometry. The other arguments are the detector, the beam energy (keV), whether \ to add Poisson noise, the number of electron trajectories to simulate, whether to simulate \ characteristic secondary fluorescence and Bremsstrahlung secondary fluorescence, the name \ to assign to the resulting spectrum.""" if e0 < 0.1: raise "The beam energy must be larger than 0.1 keV." if nTraj < 1: raise "The number of electron trajectories must be larger than or equal to 1." if dose <= 0.0: raise "The electron dose must be larger than zero." name = name.strip() if xtraParams.has_key("Postfix"): name = "%s - %s" % (name, xtraParams["Postfix"]) # Place the sample at the optimal location for the detector origin = epq.SpectrumUtils.getSamplePosition(det.getProperties()) # Create a simulator and initialize it monte = nm.MonteCarloSS() if xtraParams.has_key("Gun"): gun = xtraParams["Gun"] gun.setCenter([0.0, 0.0, -0.099]) monte.setElectronGun(gun) if xtraParams.has_key("PosX"): beamX = xtraParams["PosX"] beamY = xtraParams["PosY"] beamZ = xtraParams["PosZ"] beamNM = xtraParams["nmSize"] beam=nm.GaussianBeam(beamNM*1.0e-9) beam.setCenter([beamX, beamY, beamZ]) monte.setElectronGun(beam) chamber = monte.getChamber() if xtraParams.has_key("VP"): pathLength, gas = xtraParams["VP"] dim = 0.5 * nm.MonteCarloSS.ChamberRadius; dims = epu.Math2.plus(epu.Math2.v3(dim, dim, dim), epu.Math2.z3(2.0 * pathLength)) pt = epu.Math2.plus(origin, epu.Math2.z3(0.5 * dim)); shape = nm.MultiPlaneShape.createBlock(dims, pt, 0.0, 0.0, 0.0); msm = nm.BasicMaterialModel(gas); chamber = monte.addSubRegion(chamber, msm, shape); monte.setBeamEnergy(epq.ToSI.keV(e0)) buildSample(monte, chamber, origin, buildParams) # Add event listeners to model characteristic radiation chXR = nm3.CharacteristicXRayGeneration3.create(monte) xrel = nm3.XRayTransport3.create(monte, det, chXR) brXR = nm3.BremsstrahlungXRayGeneration3.create(monte) brem = nm3.XRayTransport3.create(monte, det, brXR) chSF, brSF, bremFluor, charFluor = None, None, None, None hasCharAcc = xtraParams.has_key('Characteristic Accumulator') and xtraParams['Characteristic Accumulator'] if sf or hasCharAcc or xtraParams.has_key("Compton"): charFluor = nm3.FluorescenceXRayGeneration3.create(monte, chXR) if xtraParams.has_key("Compton"): charFluor.setIncludeCompton(True) chSF = nm3.XRayTransport3.create(monte, det, charFluor) hasBremFluorAcc = xtraParams.has_key('Brem Fluor Accumulator') and xtraParams['Brem Fluor Accumulator'] if bf or hasBremFluorAcc: bremFluor = nm3.FluorescenceXRayGeneration3.create(monte, brXR) brSF = nm3.XRayTransport3.create(monte, det, bremFluor) hasTrans = xtraParams.has_key("Transitions") if hasTrans: if xtraParams.has_key("Emission Images"): eis = [] dim = xtraParams["Emission Images"] for xrt in xtraParams["Transitions"]: size = xtraParams["Emission Size"] ei = nm3.EmissionImage3(size, size, xrt) xrel.addXRayListener(ei) if chSF: chSF.addXRayListener(ei) if brSF: brSF.addXRayListener(ei) ei.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim) ei.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim) eis.append(ei) if hasCharAcc: cxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Characteristic", dose * 1.0e-9) xrel.addXRayListener(cxra) hasCharFluorAcc = xtraParams.has_key('Char Fluor Accumulator') and xtraParams['Char Fluor Accumulator'] if hasCharFluorAcc or chSF or sf: cfxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Characteristic Fluorescence", dose * 1.0e-9) chSF.addXRayListener(cfxra) if hasBremFluorAcc or brSF or bf: bfxra = nm3.XRayAccumulator3(xtraParams["Transitions"], "Continuum Fluorescence", dose * 1.0e-9) brSF.addXRayListener(bfxra) contImgs = [] if xtraParams.has_key('Continuum Images'): dim = xtraParams['Continuum Images'] size = xtraParams['Continuum Size'] energies = xtraParams['Continuum Energies'] for eMin, eMax in energies: ci3 = nm3.ContinuumImage3(size, size, epq.ToSI.keV(eMin), epq.ToSI.keV(eMax)) ci3.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim) ci3.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim) brem.addXRayListener(ci3) contImgs.append(ci3) doPRZ = xtraParams.has_key("PhiRhoZ") if doPRZ: depth = xtraParams["PhiRhoZ"] prz = nm3.PhiRhoZ3(xrel, origin[2] - 0.1 * depth, origin[2] + 1.1 * depth, 110) xrel.addXRayListener(prz) voxelated = xtraParams.has_key('Voxelated') vox = None if voxelated: dim = xtraParams['Voxelated'] gen = xtraParams['GeneratedV'] size = xtraParams['SizeV'] vox = nm3.VoxelatedDetector((origin[0], origin[1], origin[2] - 0.1 * size), (size, size, size), (dim, dim, dim), gen) xrel.addXRayListener(vox) doTraj = xtraParams.has_key('Trajectories') if doTraj: dim = xtraParams['Trajectories'] size = xtraParams['TrajSize'] ti = nm.TrajectoryImage(size, size, dim) ti.setXRange(origin[0] - 0.5 * dim, origin[0] + 0.5 * dim) ti.setYRange(origin[2] - 0.1 * dim, origin[2] + 0.9 * dim) monte.addActionListener(ti) defOut = (dtsa2.DefaultOutput if dtsa2.DefaultOutput else dtsa2.reportPath()) do = ("%s\\%s" % (xtraParams["Output"], dtsa2.normalizeFilename(name)) if xtraParams.has_key("Output") else "%s/%s" % (defOut, dtsa2.normalizeFilename(name))) do = do.replace("\\", "/") fdo = jio.File(do) fdo.mkdirs() doVRML = xtraParams.has_key('VRML') vrmlWr = None if doVRML: vrmlFile = jio.File.createTempFile("vrml", ".wrl", fdo) print "VRML in " + str(vrmlFile) vrmlWr = jio.FileWriter(vrmlFile) vrml = nm.TrajectoryVRML(monte, vrmlWr) vrml.setDisplayBackscatter(False) vrml.setDisplayXRayEvent(True) vrml.setMaxTrajectories(xtraParams['VRML']) vrml.setTrajectoryWidth(1.0e-9) vrml.setMaxRadius(1.0) vrml.setEmissive(True) vrml.addView("Y-Axis", epu.Math2.plus(origin, (0.0, 5.0e-6, 0.0)), origin) vrml.addView("Gun", epu.Math2.plus(origin, (0.0, 0.0, -5.0e-6)), origin) vrml.addView("X-Axis", epu.Math2.plus(origin, (-5.0e-6, 0.0, 0.0)), origin) vrml.renderSample() monte.addActionListener(vrml) scatter = None if xtraParams.has_key("Scatter"): scatter = nm.ScatterStats(epq.ToSI.eV(50.0)) monte.addActionListener(scatter) # Reset the detector and run the electrons det.reset() monte.runMultipleTrajectories(nTraj) # Get the spectrum and assign properties spec = det.getSpectrum((dose * 1.0e-9) / (nTraj * epq.PhysicalConstants.ElectronCharge)) props = spec.getProperties() props.setNumericProperty(epq.SpectrumProperties.LiveTime, dose) props.setNumericProperty(epq.SpectrumProperties.FaradayBegin, 1.0) props.setNumericProperty(epq.SpectrumProperties.BeamEnergy, e0) epq.SpectrumUtils.rename(spec, name) if withPoisson: spec = epq.SpectrumUtils.addNoiseToSpectrum(spec, 1.0) printAcc = xtraParams.has_key('Print Accumulators') and xtraParams['Print Accumulators'] if printAcc: sw0 = jio.StringWriter() sw = jio.PrintWriter(sw0) if hasTrans or scatter: pw = None if hasCharAcc or (hasBremFluorAcc and bf) or (hasCharFluorAcc and sf) or scatter: jio.File(do).mkdirs() pw = jio.PrintWriter("%s/Intensity.csv" % do) pw.println(name) if hasCharAcc: pw.println("Characteristic") cxra.dump(pw) if printAcc: sw.println("Characteristic") cxra.dump(sw) if hasBremFluorAcc and brSF and bf: pw.println("Bremsstrahlung Fluorescence") bfxra.dump(pw) if printAcc: sw.println("Bremsstrahlung Fluorescence") bfxra.dump(sw) if hasCharFluorAcc and chSF and sf: pw.println("Characteristic Fluorescence") cfxra.dump(pw) if printAcc: sw.println("Characteristic Fluorescence") cfxra.dump(sw) if printAcc: print sw0.toString() sw.close() sw0.close() if scatter: scatter.header(pw) scatter.dump(pw) if pw: pw.close() imgs = [] if xtraParams.has_key("Emission Images"): nm3.EmissionImageBase.scaleEmissionImages(eis) print eis print do nm3.EmissionImage3.dumpToFiles(eis, do) print u"Writing emission images to %s" % do imgs.extend(eis) if xtraParams.has_key("Continuum Images"): imgs.extend(contImgs) nm3.EmissionImageBase.scaleEmissionImages(imgs) print contImgs print do nm3.ContinuumImage3.dumpToFiles(contImgs, do) print u"Writing continuum images to %s" % do if doPRZ: jio.File(do).mkdirs() pw = jio.PrintWriter(u"%s/PhiRhoZ.csv" % do) prz.write(pw) pw.close() print u"Writing emission images to %s" % do if doTraj: ti.dumpToFile(do) print u"Writing trajectory images to %s" % do if vrmlWr: vrmlWr.close() if vox: jio.File(do).mkdirs() objs = list(vox.getAccumulatorObjects()) xx = {} for obj in objs: iio.write(vox.createXZSum(400, obj), "png", jio.File(do, "Voxelated[XZ,Sum][%s].png" % obj)) iio.write(vox.createXYSum(400, obj), "png", jio.File(do, "Voxelated[XY,Sum][%s].png" % obj)) iio.write(vox.createXZView(400, obj), "png", jio.File(do, "Voxelated[XZ, Max][%s].png" % obj)) iio.write(vox.createXYView(400, obj), "png", jio.File(do, "Voxelated[XY, Max][%s].png" % obj)) vox.writeXZPlanar(400, obj, jio.File(do, "Voxilated[XZ,planar,%s].tif" % obj)) vox.writeXYPlanar(400, obj, jio.File(do, "Voxilated[XY,planar,%s].tif" % obj)) for f in (0.1, 0.5, 0.8, 0.9): iio.write(vox.createXZFraction(400, obj, f), "png", jio.File(do, "Voxelated[XZ,f=%g][%s].png" % (f, obj))) xx[obj] = vox.createRadialCDF(origin, obj) hdr = "Radius" for obj in objs: hdr = "%s\t%s" % (hdr, obj) print hdr first = xx[objs[0]] for i, (d, f) in enumerate(first): ln = "%g" % d for obj in objs: rcdf = xx[obj][i] ln = "%s\t%g" % (ln, rcdf[1]) print ln #if bremFluor: #print "Stats[Scale] = %s" % bremFluor.getScaleStats() return dtsa2.wrap(spec)
def make_image(width, height, file, type): image = generate_image(width, height) ImageIO.write(image, type, File(file))
//Before is how to change ByteArray back to Image ByteArrayInputStream bis = new ByteArrayInputStream(bytes); Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg"); //ImageIO is a class containing static convenience methods for locating ImageReaders //and ImageWriters, and performing simple encoding and decoding. ImageReader reader = (ImageReader) readers.next(); Object source = bis; // File or InputStream, it seems file is OK ImageInputStream iis = ImageIO.createImageInputStream(source); //Returns an ImageInputStream that will take its input from the given Object reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); Image image = reader.read(0, param); //got an image file BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); //bufferedImage is the RenderedImage to be written Graphics2D g2 = bufferedImage.createGraphics(); g2.drawImage(image, null, null); File imageFile = new File("C:\\newrose2.jpg"); ImageIO.write(bufferedImage, "jpg", imageFile); //"jpg" is the format of the image //imageFile is the file to be written to. System.out.println(imageFile.getPath()); } }
def save_editable_image_as_png_to_disk(editable_image, path, overwrite=False): assert isinstance(editable_image, BufferedImage), "No *editable* image (instance of ImageIO) given!" assert overwrite == True or os.path.isfile(path) == False, "File already exists" ImageIO.write(editable_image, "png", File(path))
def write_image_to_disk(self, image_path, image): os = FileOutputStream(image_path) ImageIO.write( image, "png", os ) os.flush() os.close()
def convertPNG(self, isStageCostume, costume_info, costume_src_path , costume_dest_path): import java.io.File new_image = svgtopng._translation(costume_src_path, costume_info["rotationCenterX"], costume_info["rotationCenterY"]) ImageIO.write(new_image, "png", java.io.File(costume_dest_path)) if JsonKeys.COSTUME_RESOLUTION in costume_info: self.resize_png(costume_dest_path, costume_dest_path, costume_info[JsonKeys.COSTUME_RESOLUTION])
def write_image_to_disk(self, image_path, image): os = FileOutputStream(image_path) ImageIO.write(image, "png", os) os.flush() os.close()
def convert(input_svg_path, rotation_x, rotation_y): assert isinstance(input_svg_path, (str, unicode)) assert os.path.splitext(input_svg_path)[1] == ".svg" input_file_name = os.path.splitext(input_svg_path)[0] output_png_path = "{}_rotX_{}_rotY_{}.png".format(input_file_name, rotation_x, rotation_y) _log.info(" converting '%s' to Pocket Code compatible png '%s'", input_svg_path, output_png_path) output_svg_path = input_svg_path.replace(".svg", "_modified.svg") output_svg_URI = Paths.get(output_svg_path).toUri().toURL().toString() if os.path.exists(output_png_path): _log.info(" nothing to do: '%s' already exists", output_png_path) # remove temporary files if os.path.exists(output_svg_path): os.remove(output_svg_path) return output_png_path # avoid duplicate conversions! png_ostream = None error = None try: _parse_and_rewrite_svg_file(input_svg_path, output_svg_path) input_svg_image = TranscoderInput(output_svg_URI) output_png_image = TranscoderOutput(FileOutputStream(output_png_path)) _log.info(" converting '%s' to Pocket Code compatible png '%s'", input_svg_path, output_png_path) png_converter = PNGTranscoder() png_converter.transcode(input_svg_image, output_png_image) assert os.path.exists(output_png_path) # TODO: uncomment this once all remaining bugs have been fixed! final_image = _translation(output_png_path, rotation_x, rotation_y) if final_image is None: raise RuntimeError("...") from javax.imageio import ImageIO from java.io import File ImageIO.write(final_image, "PNG", File(output_png_path)) return output_png_path except BaseException as err: import traceback import sys exc_info = sys.exc_info() _log.error(err) _log.error(traceback.format_exc()) _log.error(exc_info) error = common.ScratchtobatError( "PNG to SVG conversion call failed for: %s" % input_svg_path) finally: # free resources if png_ostream != None: png_ostream.flush() png_ostream.close() # remove temporary files if os.path.exists(output_svg_path): os.remove(output_svg_path) if error != None: raise error
def convert(input_svg_path, rotation_x, rotation_y): assert isinstance(input_svg_path, (str, unicode)) assert os.path.splitext(input_svg_path)[1] == ".svg" input_file_name = os.path.splitext(input_svg_path)[0] output_png_path = "{}_rotX_{}_rotY_{}.png".format(input_file_name, rotation_x, rotation_y) _log.info(" converting '%s' to Pocket Code compatible png '%s'", input_svg_path, output_png_path) output_svg_path = input_svg_path.replace(".svg", "_modified.svg") output_svg_URI = Paths.get(output_svg_path).toUri().toURL().toString() if os.path.exists(output_png_path): _log.error(" '%s' already exists", output_png_path) #assert False # "Still a Duplicate?" # remove temporary files if os.path.exists(output_svg_path): os.remove(output_svg_path) return output_png_path # avoid duplicate conversions! png_ostream = None error = None try: _parse_and_rewrite_svg_file(input_svg_path, output_svg_path) input_svg_image = TranscoderInput(output_svg_URI) output_png_image = TranscoderOutput(FileOutputStream(output_png_path)) _log.info(" converting '%s' to Pocket Code compatible png '%s'", input_svg_path, output_png_path) png_converter = PNGTranscoder() png_converter.transcode(input_svg_image, output_png_image) assert os.path.exists(output_png_path) final_image = _translation(output_png_path, rotation_x, rotation_y) if final_image is None: raise RuntimeError("...") from javax.imageio import ImageIO from java.io import File ImageIO.write(final_image, "PNG", File(output_png_path)) return output_png_path except BaseException as err: import traceback import sys exc_info = sys.exc_info() _log.error(err) _log.error(traceback.format_exc()) _log.error(exc_info) error = common.ScratchtobatError("SVG to PNG conversion call failed for: %s" % input_svg_path) finally: # free resources if png_ostream != None: png_ostream.flush() png_ostream.close() # remove temporary files if os.path.exists(output_svg_path): os.remove(output_svg_path) if error != None: raise error