def raster(self, filename, client): """Takes a filename and converts it to a raster image reportlab can process""" if not os.path.exists(filename): log.error("Missing image file: %s",filename) return missing try: # First try to rasterize using the suggested backend backend = self.get_backend(filename, client)[1] return backend.raster(filename, client) except: pass # Last resort: try everything if sys.platform[0:4] == 'java': try: from javax.imageio import ImageIO from java.io import File iis = ImageIO.createImageInputStream(File(filename)) readers = ImageIO.getImageReaders(iis) if readers.hasNext(): reader = readers.next() reader.setInput(iis, True) metadata = reader.getImageMetadata(0) # this means imageio can read it return filename else: log.warning("Java's ImageIO cannot read the file [%s]", filename) except Exception, error: log.warning("Could not use Java's ImageIO to read the file [%s]: %s", filename, str(error))
def __init__(self,hostname): self.hostname=hostname JPanel.__init__(self,BorderLayout()) self.cbActionListener=foo2(self) #imglist=os.listdir('./img') #try:imglist.remove('.svn') #except:pass imglist=['01-CircleOfFifths.gif','Fifths.png','circle-o-fifths.jpg','Circle_Of_Fifths.gif','Keywheel.gif','circle-of-fifths.gif','ColorFifths.jpg','cof.gif'] self.cb=JComboBox(imglist,actionListener=self.cbActionListener)# #self.cb.addItemListener(self.cbCB) tb=JPanel() tb.setLayout(FlowLayout(FlowLayout.CENTER)) tb.add(self.cb) self.add(tb,'Center') self.img=None if hostname[0:7]=='http://': self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+imglist[0])) else: self.img=ImageIO.read(File(self.hostname+'img/'+imglist[0])) icon=ImageIcon(self.img) self.label=JLabel(icon) self.add(self.label,'North')
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 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 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 outputFiles(self, filename, attachLogo=False, logoText=None): rendered = self.getTarget().screenshot() if attachLogo: from java.awt.image import BufferedImage noaa = File(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logos/noaalogo2.png')) nws = File(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'logos/nwslogo.png')) noaaImage = ImageIO.read(noaa) nwsImage = ImageIO.read(nws) height = rendered.getHeight() + noaaImage.getHeight() finalBuf = BufferedImage(rendered.getWidth(), height, BufferedImage.TYPE_INT_ARGB) graphics = finalBuf.createGraphics() graphics.drawImage(rendered, 0, 0, None) graphics.drawImage(noaaImage, 0, rendered.getHeight(), None) graphics.fillRect(noaaImage.getWidth(), rendered.getHeight(), rendered.getWidth() - noaaImage.getWidth() - nwsImage.getWidth(), rendered.getHeight()) if logoText is not None: from java.awt import Color graphics.setColor(Color.BLACK) graphics.setFont(self.getAWTFont(self.getTarget().getDefaultFont())) fm = graphics.getFontMetrics() textBounds = fm.getStringBounds(logoText, graphics) graphics.drawString(logoText, int((rendered.getWidth() - textBounds.getWidth()) / 2), \ int(rendered.getHeight() + (noaaImage.getHeight() / 2) + textBounds.getHeight() / 2)) graphics.drawImage(nwsImage, finalBuf.getWidth() - nwsImage.getWidth(), rendered.getHeight(), None) finalBuf.flush() self.outputImage(finalBuf, filename) else: self.outputImage(rendered, filename)
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 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 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 outputFiles(self, filename, attachLogo=False, logoText=None): rendered = self.getTarget().screenshot() if attachLogo: from java.awt.image import BufferedImage from com.raytheon.uf.common.localization import PathManagerFactory noaa = 'pyViz/logos/noaalogo2.png' nws = 'pyViz/logos/nwslogo.png' pathMgr = PathManagerFactory.getPathManager() noaa = pathMgr.getStaticFile(noaa) nws = pathMgr.getStaticFile(nws) noaaImage = ImageIO.read(noaa) nwsImage = ImageIO.read(nws) height = rendered.getHeight() + noaaImage.getHeight() finalBuf = BufferedImage(rendered.getWidth(), height, BufferedImage.TYPE_INT_ARGB) graphics = finalBuf.createGraphics() graphics.drawImage(rendered, 0, 0, None) graphics.drawImage(noaaImage, 0, rendered.getHeight(), None) graphics.fillRect(noaaImage.getWidth(), rendered.getHeight(), rendered.getWidth() - noaaImage.getWidth() - nwsImage.getWidth(), rendered.getHeight()) if logoText is not None: from java.awt import Color from com.raytheon.uf.viz.core.font import FontAdapter graphics.setColor(Color.BLACK) graphics.setFont(FontAdapter.getAWTFont(self.getTarget().getDefaultFont())) fm = graphics.getFontMetrics() textBounds = fm.getStringBounds(logoText, graphics) graphics.drawString(logoText, int((rendered.getWidth() - textBounds.getWidth()) / 2), \ int(rendered.getHeight() + (noaaImage.getHeight() / 2) + textBounds.getHeight() / 2)) graphics.drawImage(nwsImage, finalBuf.getWidth() - nwsImage.getWidth(), rendered.getHeight(), None) finalBuf.flush() self.outputImage(finalBuf, filename) else: self.outputImage(rendered, filename)
def test_parse_svgfile_and_convert_to_png_antenna(self): img_proc_dir = os.path.join(helpers.APP_PATH, "test", "res", "img_proc_png") input_svg_path = os.path.join(img_proc_dir, "input_antenna.svg") expected_image_path = os.path.join(img_proc_dir, "expected_antenna.png") assert os.path.exists(input_svg_path) rotation_x, rotation_y = 53, 43 output_png_path = svgtopng.convert(input_svg_path, rotation_x, rotation_y) from javax.imageio import ImageIO from java.io import File bufferd_image = ImageIO.read(File(output_png_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() output_image_matrix = [[bufferd_image.getRGB(i, j) for j in xrange(height)] for i in xrange(width)] bufferd_image = ImageIO.read(File(expected_image_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() expected_image_matrix = [[bufferd_image.getRGB(i, j) for j in xrange(height)] for i in xrange(width)] for i in xrange(width): for j in xrange(height): exp_rgb_val = expected_image_matrix[i][j] result_rgb_val = output_image_matrix[i][j] assert exp_rgb_val == result_rgb_val
def test_parse_svgfile_and_convert_to_png_background(self): img_proc_dir = os.path.join(helpers.APP_PATH, "test", "res", "img_proc_png") input_svg_path = os.path.join(img_proc_dir, "input_background.svg") expected_image_path = os.path.join(img_proc_dir, "expected_background.png") assert os.path.exists(input_svg_path) rotation_x, rotation_y = 255, 180 output_png_path = svgtopng.convert(input_svg_path, rotation_x, rotation_y, ns_registry_lock) from javax.imageio import ImageIO from java.io import File bufferd_image = ImageIO.read(File(output_png_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() output_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] bufferd_image = ImageIO.read(File(expected_image_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() expected_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] for i in xrange(width): for j in xrange(height): exp_rgb_val = expected_image_matrix[i][j] result_rgb_val = output_image_matrix[i][j] assert exp_rgb_val == result_rgb_val
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 image_byte_array(self): baos = ByteArrayOutputStream(); ImageIO.write( self.image(), "png", baos ); baos.flush(); image_bytes = baos.toByteArray(); baos.close() return image_bytes
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 test_parse_svgfile_and_convert_to_png_hat_q4(self): img_proc_dir = os.path.join(helpers.APP_PATH, "test", "res", "img_proc_png") input_svg_path = os.path.join(img_proc_dir, "input_hat.svg") assert os.path.exists(input_svg_path) rotation_x, rotation_y = 97, -51 expected_image_path = os.path.join( img_proc_dir, "expected_hat" + "_rotX_" + str(rotation_x) + "_rotY_" + str(rotation_y) + ".png") output_png_path = svgtopng.convert(input_svg_path, rotation_x, rotation_y) from javax.imageio import ImageIO from java.io import File bufferd_image = ImageIO.read(File(output_png_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() output_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] bufferd_image = ImageIO.read(File(expected_image_path)) width, height = bufferd_image.getWidth(), bufferd_image.getHeight() expected_image_matrix = [[ bufferd_image.getRGB(i, j) for j in xrange(height) ] for i in xrange(width)] for i in xrange(width): for j in xrange(height): exp_rgb_val = expected_image_matrix[i][j] result_rgb_val = output_image_matrix[i][j] assert exp_rgb_val == result_rgb_val
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 _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 jpg2bmp(src): # load jpg b = bmp_name(src) f = File(src) image = ImageIO.read(f) output = File(b) ImageIO.write(image,"bmp",output)
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 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 getimage(self) : if not os.path.exists('tools/image.png') : imagedata = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJ\nbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdp\nbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6\neD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEz\nNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJo\ndHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlw\ndGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAv\nIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RS\nZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpD\ncmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNl\nSUQ9InhtcC5paWQ6MzZDNTFCOUZGNUQ5MTFERkE0Mzk4NUE5OTMzRTQwNzkiIHhtcE1NOkRvY3Vt\nZW50SUQ9InhtcC5kaWQ6MzZDNTFCQTBGNUQ5MTFERkE0Mzk4NUE5OTMzRTQwNzkiPiA8eG1wTU06\nRGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDozNkM1MUI5REY1RDkxMURGQTQz\nOTg1QTk5MzNFNDA3OSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDozNkM1MUI5RUY1RDkxMURG\nQTQzOTg1QTk5MzNFNDA3OSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1w\nbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pms/CZAAAAECSURBVHjaYtRe+JiBloCJgcZg1IIhZYHV\ntzNARKoFLESqY/3/p+DNHCDjtKzBb0YW6vvA9/Numd/Pgcj/007qBxHfvy9p75ZC2CnvlwO5VLYg\n7d0Svr+foZb9/QzkUtMC1Z/3A1CDBcgFClLNgqK3s5j+/0PR8/8fUJA6Fth+PaX//RqmOFAQKEWp\nBcCkmft2Hi5ZoBRQAUUWRHzcCEyXuGSBUkAF5Fsg+udtwvtV+DUDFQCVkWlB9ruFnP9+4NcMVABU\nRo4FwFTo9vkgMXEIVIY/yWIvVTR+3dnI505kQgQqvs2uSJoF/nltxOdVVQaGzfNdRyucUQtGLRi1\ngAIAEGAAimxsT0J9RpkAAAAASUVORK5CYII=\n' actual_image = base64.b64decode(imagedata) from java.io import ByteArrayInputStream stream = ByteArrayInputStream(actual_image) self._image = ImageIO.read(stream); else : self._image = ImageIO.read(File('tools/image.png'))
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 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 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 animated(images, file=None, delay=300, loop=False): """ Generates an anmiated GIF. The *images* parameter is a sequence of objects that can be read as GIF images, such as an array of bytes. The *file* parameter specifies the file to generate. When omitted the resulting animated GIF is returned from this function as an array byte. The *delay* specifies the frame rate in milliseconds. The *loop* parameter specifies whether the animated GIF should loop continously. """ from com.sun.media.imageioimpl.plugins.gif import GIFImageWriter from com.sun.media.imageioimpl.plugins.gif import GIFImageWriterSpi out = ByteArrayOutputStream() if file is None else util.toFile(file) ios = ImageIO.createImageOutputStream(out) w = GIFImageWriter(GIFImageWriterSpi()) w.setOutput(ios) w.prepareWriteSequence(None) wp = w.getDefaultWriteParam() wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) wp.setCompressionType('LZW') wp.setCompressionQuality(0.75) for img in images: iis = ImageIO.createImageInputStream(util.toInputStream(img)) ri = ImageIO.read(iis) md = w.getDefaultImageMetadata(ImageTypeSpecifier(ri), wp) t = IIOMetadataTree(md) t.set('GraphicControlExtension', delayTime=delay / 10) if loop is True: n = t.set('ApplicationExtensions', 'ApplicationExtension', applicationID='NETSCAPE', authenticationCode='2.0') n.setUserObject(jarray.array([0x1, 0, 0], 'b')) t.commit() w.writeToSequence(IIOImage(ri, None, md), wp) w.endWriteSequence() ios.flush() ios.close() if file is None: return out.toByteArray()
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 cbCB(self,e): try: item=self.cb.getSelectedItem() if DEBUG:print item if self.hostname[0:7]=='http://': self.img=ImageIO.read(URL(self.hostname+'/static/sightreadingtrainer/img/'+item)) else: self.img=ImageIO.read(File(self.hostname+'img/'+item)) if DEBUG:print self.img icon=ImageIcon(self.img) self.label.setIcon(icon) except Exception,e: if DEBUG:print e
def animated(images, file=None, delay=300, loop=False): """ Generates an anmiated GIF. The *images* parameter is a sequence of objects that can be read as GIF images, such as an array of bytes. The *file* parameter specifies the file to generate. When omitted the resulting animated GIF is returned from this function as an array byte. The *delay* specifies the frame rate in milliseconds. The *loop* parameter specifies whether the animated GIF should loop continously. """ from com.sun.media.imageioimpl.plugins.gif import GIFImageWriter from com.sun.media.imageioimpl.plugins.gif import GIFImageWriterSpi out = ByteArrayOutputStream() if file is None else util.toFile(file) ios = ImageIO.createImageOutputStream(out) w = GIFImageWriter(GIFImageWriterSpi()) w.setOutput(ios) w.prepareWriteSequence(None) wp = w.getDefaultWriteParam() wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) wp.setCompressionType('LZW') wp.setCompressionQuality(0.75) for img in images: iis = ImageIO.createImageInputStream(util.toInputStream(img)) ri = ImageIO.read(iis) md = w.getDefaultImageMetadata(ImageTypeSpecifier(ri),wp) t = IIOMetadataTree(md) t.set('GraphicControlExtension', delayTime=delay/10) if loop is True: n = t.set('ApplicationExtensions', 'ApplicationExtension', applicationID='NETSCAPE', authenticationCode='2.0') n.setUserObject(jarray.array([0x1,0, 0], 'b')) t.commit() w.writeToSequence(IIOImage(ri, None, md), wp) w.endWriteSequence() ios.flush() ios.close() if file is None: return out.toByteArray()
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 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 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 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 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 _read_image(self, fp): if sys.platform[0:4] == "java": from javax.imageio import ImageIO return ImageIO.read(fp) else: return Image.open(fp)
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 read(self, filename): """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels.""" # JEM working directory fix (see above) filename = fixWorkingDirForJEM(filename) # does nothing if not in JEM # *** #print "fixWorkingDirForJEM( filename ) =", filename file = File(filename) # read file from current directory self.image = ImageIO.read(file) self.width = self.image.getWidth(None) self.height = self.image.getHeight(None) pixels = [] # initialize list of pixels # load pixels from image for row in range(self.height): pixels.append([]) # add another empty row for col in range(self.width): # now, populate row with pixels color = Color(self.image.getRGB(col, row)) # get pixel's color RGBlist = [color.getRed(), color.getGreen(), color.getBlue() ] # create list of RGB values (0-255) pixels[-1].append( RGBlist) # add a pixel as (R, G, B) values (0-255, each) # now, pixels have been loaded from image file, so create an image self.setPixels(pixels)
def loadImage(filepath): fp = open(filepath, 'r') image = ImageIO.read(fp) fp.close() return image
def readImg(filename): from java.io import File from javax.imageio import ImageIO import sys, os scriptDir = os.path.dirname(sys.argv[0]) return ImageIO.read( File(os.path.join(scriptDir, "stateDetectionImages", filename)))
def read(self, filename): """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels.""" # JEM working directory fix (see above) filename = fixWorkingDirForJEM( filename ) # does nothing if not in JEM # *** #print "fixWorkingDirForJEM( filename ) =", filename file = File(filename) # read file from current directory self.image = ImageIO.read(file) self.width = self.image.getWidth(None) self.height = self.image.getHeight(None) pixels = [] # initialize list of pixels # load pixels from image for row in range(self.height): pixels.append( [] ) # add another empty row for col in range(self.width): # now, populate row with pixels color = Color(self.image.getRGB(col, row)) # get pixel's color RGBlist = [color.getRed(), color.getGreen(), color.getBlue()] # create list of RGB values (0-255) pixels[-1].append( RGBlist ) # add a pixel as (R, G, B) values (0-255, each) # now, pixels have been loaded from image file, so create an image self.setPixels(pixels)
def gui_open(path): label = JLabel(ImageIcon(ImageIO.read(File(URL(path).getFile())))) frame = JFrame() frame.getContentPane().add(label) frame.pack() frame.setLocation(200, 200) frame.setVisible(True)
def getColorFormImage(fn): f = jf.File(fn) img = IIO.read(f) x = img.getWidth()/2 y = img.getHeight()/2 #print "gk "+str(x) +str(y) return JColor(img.getRGB(x,y))
def _read_image(self,fp): if sys.platform[0:4] == 'java': from javax.imageio import ImageIO return ImageIO.read(fp) else: import PIL.Image return PIL.Image.open(fp)
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 json_encoded_values(im_paths): import simplejson as json list_of_dicts = [] list_of_names = ('string', 'base64', 'hash') for im_pth in im_paths: im = ImageIO.read(File(im_pth)) list_of_dicts.append(dict( color_layout=dict( zip(list_of_names, test_color_layout(im, silence=True))), edge_histogram=dict( zip(list_of_names, test_edge_histogram(im, silence=True))), phog=dict( zip(list_of_names, test_PHOG(im, silence=True))), opponent_histogram=dict( zip(list_of_names, test_opponent_histogram(im, silence=True))), # jcd=dict( # zip(list_of_names, # test_JCD(im, silence=True))), )) print json.dumps(list_of_dicts, indent=4)
def readable_values(im_paths): from os.path import basename for im_pth in im_paths: im = ImageIO.read(File(im_pth)) print "" print "-" * 120 print "" print "IMAGE: %s" % basename(im_pth) for histoval in test_color_layout(im): print histoval for histoval in test_edge_histogram(im): print histoval for histoval in test_PHOG(im): print histoval for histoval in test_opponent_histogram(im): print histoval #for histoval in test_JCD(im): # print histoval print ""
def average_hash_and_sizes(self): height = 0 width = 0 if isJython(): image = ImageIO.read(File(self.image_path)) height = image.getHeight() width = image.getWidth() newImage = BufferedImage(self.hash_size, self.hash_size, BufferedImage.TYPE_INT_ARGB) g = newImage.createGraphics() g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC) g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY) g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) g.drawImage(image, 0, 0, self.hash_size, self.hash_size, None) g.dispose() allchannelpixels = [[], [], [], []] for i in range(self.hash_size): for j in range(self.hash_size): pixel = int(newImage.getRGB(i, j)) allchannelpixels[0].append((pixel >> 16) & 0xFF) allchannelpixels[1].append((pixel >> 8) & 0xFF) allchannelpixels[2].append((pixel) & 0xFF) allchannelpixels[3].append((pixel >> 24) & 0xFF) elif isIronPython(): srcImage = Bitmap(self.image_path) height = srcImage.Height width = srcImage.Width newImage = Bitmap(self.hash_size, self.hash_size) gr = Graphics.FromImage(newImage) gr.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias gr.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic gr.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality gr.DrawImage(srcImage, Rectangle(0, 0, self.hash_size, self.hash_size)) allchannelpixels = [[], [], [], []] for i in range(self.hash_size): for j in range(self.hash_size): pixel = newImage.GetPixel(i, j) allchannelpixels[0].append(int(pixel.R)) allchannelpixels[1].append(int(pixel.G)) allchannelpixels[2].append(int(pixel.B)) allchannelpixels[3].append(int(pixel.A)) else: self.image = Image.open(self.image_path) width, height = self.image.size image = self.image.resize((self.hash_size, self.hash_size), Image.ANTIALIAS) # image.show() allchannelpixels = [ list(channel.getdata()) for channel in image.split() ] bits = [] for pixels in allchannelpixels: bits.append(self.getBitString(pixels)) return bits, width, height
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 _read_image(self, fp): if sys.platform[0:4] == 'java': from javax.imageio import ImageIO from java.io import ByteArrayInputStream input_stream = ByteArrayInputStream(fp.read()) return ImageIO.read(input_stream) elif PILImage: return PILImage.open(fp)
def __init__(self, actions, mapname, colormap, name="PlaceCellEnvironment", imgsize=(1.0, 1.0), dx=0.01, placedev=0.1, num_places=None): """Initialize environment variables. :param actions: actions available to the system :type actions: list of tuples (action_name,action_vector) :param mapname: name of file describing environment map :param colormap: dict mapping pixel colours to labels :param name: name for environment :param imgsize: width of space represented by the map image :param dx: distance agent moves each timestep :param placedev: standard deviation of gaussian place cell activations :param num_places: number of placecells to use (if None it will attempt to fill the space) """ EnvironmentTemplate.__init__(self, name, 2, actions) # parameters self.colormap = colormap self.rewardamount = 0 # number of timesteps spent in reward # number of timesteps to spend in reward before agent is reset # note: convenient to express this as time_in_reward / dt self.rewardresetamount = 0.6 / 0.001 self.num_actions = len(actions) self.imgsize = [float(x) for x in imgsize] self.dx = dx self.placedev = placedev self.num_places = num_places self.optimal_move = None self.defaultreward = -0.075 # load environment self.map = ImageIO.read(File(HRLutils.datafile(mapname))) # generate place cells self.gen_placecells(min_spread=1.0 * placedev) # initial conditions self.state = self.random_location(avoid=["wall", "target"]) self.place_activations = [0 for _ in self.placecells] self.create_origin("place", lambda: self.place_activations) # note: making the value small, so that the noise node will give us # some random exploration as well self.create_origin( "optimal_move", lambda: [0.1 if self.optimal_move == a[0] else 0.0 for a in self.actions])
def create_icon(self, path): try: im = ImageIO.read(File(path)) except: raise im = im.getScaledInstance(32, 32, Image.SCALE_SMOOTH) icon = ImageIcon(im) return icon
def next(self): image_file_name = self.iterator.next() #Find example label label = image_file_name[0:image_file_name.index('_')] #Get the image as an image buffer image_file = File(dir_path, image_file_name) image_is = FileInputStream(image_file) buffered_image = ImageIO.read(image_is) #Return label and image tuple return (label, buffered_image)