Exemple #1
0
   def __init__(self, filename, width=None, height=None): 
      """Create an image from a file, or an empty (black) image with specified dimensions."""
      
      # Since Python does not allow constructors with different signatures,
      # the trick is to reuse the first argument as a filename or a width.
      # If it is a string, we assume they want is to open a file.
      # If it is an int, we assume they want us to create a blank image.
      
      if type(filename) == type(""):  # is it a string?
         self.filename = filename        # treat is a filename
         self.image = BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB)  # create a dummy image
         self.read(filename)             # and read external image into ti
                  
      elif type(filename) == type(1): # is it a int?
      
         # create blank image with specified dimensions
         self.filename = "Untitled"
         self.width = filename       # holds image width (shift arguments)
         self.height = width         # holds image height
         self.image = BufferedImage(self.width, self.height, BufferedImage.TYPE_INT_RGB)  # holds image buffer (pixels)
      else:
         raise  TypeError("Image(): first argument must a filename (string) or an blank image width (int).")
         
      # display image
      self.display = JFrame()      # create frame window to hold image
      icon = ImageIcon(self.image) # wrap image appropriately for displaying in a frame
      container = JLabel(icon)         
      self.display.setContentPane(container)  # and place it

      self.display.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
      self.display.setTitle(self.filename)
      self.display.setResizable(False)
      self.display.pack()
      self.display.setVisible(True)
Exemple #2
0
def getContentPane():
    global contentPane
    global REMAP_WIDTH
    global REMAP_HEIGHT
    global MARGIN
    if not contentPane:
        global mainScreen
        global mainScreenImg
        mainScreen = JLabel()

        cursorImg = BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB)
        blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, Point(0,0), "blank cursor")
        mainScreen.setCursor(blankCursor)
        mainScreen.setPreferredSize(
                Dimension(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN))
        mainScreen.setText("main screen!")
        image = BufferedImage(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN
                , BufferedImage.TYPE_INT_ARGB)
        g = image.createGraphics()
        g.setColor(Color.BLACK)
        g.fillRect(0, 0, REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN)
        g.setColor(Color.WHITE)
        g.setFont(Font("Serif", Font.BOLD, 20))
        g.drawString("Cursor will display on your device.", 50, 30)
        mainScreenImg = image
        mainScreen.setIcon(swing.ImageIcon(image))

        mouseListener = ScrMouseListener()
        mainScreen.addMouseListener(mouseListener)
        mainScreen.addMouseMotionListener(mouseListener)
        mainScreen.addMouseWheelListener(mouseListener)

        keyListener = ScrKeyListener()
        mainScreen.addKeyListener(keyListener)
        
        mainScreen.setFocusable(True)

        scrPanel = JPanel()
        scrPanel.setLayout(BoxLayout(scrPanel, BoxLayout.Y_AXIS))
        scrPanel.add(mainScreen)


        contentPane = JPanel()
        contentPane.setLayout(BorderLayout())
        contentPane.add(scrPanel, BorderLayout.WEST)
#        contentPAne.add(controlPanel(). BorderLayout.EAST)

    return contentPane
Exemple #3
0
def levels(src, low=0, high=1, low_out=0, high_out=1):
    '''
    A filter which allows levels adjustment on an image.
    
    :param src: (*image*) Source image.
    :param low: (*float*) Low level.
    :param high: (*float*) High level.
    :param low_out: (*float*) Low output level.
    :param high_out: (*float*) High output level.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None

    filter = LevelsFilter()
    filter.setLowLevel(low)
    filter.setHighLevel(high)
    filter.setLowOutputLevel(low_out)
    filter.setHighOutputLevel(high_out)
    dst = BufferedImage(image.getWidth(), image.getHeight(),
                        BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #4
0
def threshold(src, t=None, lt=127, ut=127, white=None, black=None):
    '''
    A filter which performs a threshold operation on an image.
    
    :param src: (*image*) Source image.
    :param t: (*float*) Threshold.
    :param lt: (*float*) Lower threshold.
    :param ut: (*float*) Upper threshold.
    :param white: (*int*) The color to be used for pixels above the upper threshold.
    :param black: (*int*) The color to be used for pixels blow the lower threshold.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None

    if t is None:
        filter = ThresholdFilter()
        filter.setLowerThreshold(lt)
        filter.setUpperThreshold(ut)
    else:
        filter = ThresholdFilter(t)
    if not white is None:
        filter.setWhite(white)
    if not black is None:
        filter.setBlack(black)
    dst = BufferedImage(image.getWidth(), image.getHeight(),
                        BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #5
0
def tritone(src, shadow=None, mid=None, high=None):
    '''
    A filter which performs a tritone conversion on an image. Given three colors
    for shadows, midtones and highlights, it converts the image to grayscale and
    then applies a color mapping based on the colors.
    
    :param src: (*image*) Source image.
    :param shadow: (*int*) Shadow color.
    :param mid: (*int*) Midtone color.
    :param high: (*int*) Highlight color
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None

    filter = TritoneFilter()
    if not shadow is None:
        filter.setShadowColor(shadow)
    if not mid is None:
        filter.setMidColor(mid)
    if not high is None:
        filter.setHighColor(high)
    dst = BufferedImage(image.getWidth(), image.getHeight(),
                        BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #6
0
    def run(self):
        try:
            filepath = self.makeFilePath()
            if os.path.exists(filepath):
                return

            x, y, k = self.coords
            width, height, n_layers = self.dimensions

            # Cube's field of view in XY
            fov = Rectangle(x, y, width, height)

            # Join the bounds of the layers
            r = None
            for b in self.bounds[k:min(k + n_layers, len(bounds))]:
                if r is None:
                    r = Rectangle(b.x, b.y, b.width, b.height)
                else:
                    r.add(b)

            if not fov.intersects(r):
                # Would be empty
                return

            drawImage = Graphics2D.getDeclaredMethod(
                "drawImage", [Image, AffineTransform, ImageObserver])
            drawImage.setAccessible(True)
            dispose = Graphics.getDeclaredMethod("dispose", [])
            dispose.setAccessible(True)

            # Populate and write cube
            stack = ImageStack(width, height)
            for layer in self.layers[k:min(k + n_layers, len(self.layers))]:
                img = layer.getProject().getLoader().getFlatAWTImage(
                    layer, fov, 1.0, -1, ImagePlus.GRAY8, Patch, None, False,
                    Color.black)
                bi = BufferedImage(img.getWidth(None), img.getHeight(None),
                                   BufferedImage.TYPE_BYTE_GRAY)
                g = bi.createGraphics()
                aff = AffineTransform(1, 0, 0, 1, 0, 0)
                #g.drawImage(img, aff, None) # Necessary to bypass issues that result in only using 7-bits and with the ByteProcessor constructor
                drawImage.invoke(g, [img, aff, None])
                #g.dispose()
                dispose.invoke(g, [])
                g = None
                img = None
                stack.addSlice("", ByteProcessor(bi))
                bi.flush()
                bi = None

            imp = ImagePlus("x=%s y=%s k=%s" % (x, y, k), stack)
            Utils.ensure(filepath)
            FileSaver(imp).saveAsZip(filepath)
            imp.flush()
            imp = None
        except:
            e = sys.exc_info()
            System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" +
                               str(e[2]))
            System.out.println(traceback.format_exception(e[0], e[1], e[2]))
Exemple #7
0
 def run(self):
     try:
         bounds = self.layer.getMinimalBoundingBox(Patch, True)
         filepath = os.path.join(
             self.target_dir, "section-" + str(self.i).zfill(5) + "-[x=" +
             str(bounds.x) + "-y=" + str(bounds.y) + "-width=" +
             str(bounds.width) + "-height=" + str(bounds.height) + "].zip")
         if os.path.exists(filepath):
             System.out.println("Skipping: " + filepath)
             return
         # Export
         System.out.println("Preparing: " + os.path.split(filepath)[1])
         img = self.layer.getProject().getLoader().getFlatAWTImage(
             self.layer, bounds, 1.0, -1, ImagePlus.GRAY8, Patch, None,
             False, Color.black)
         bi = BufferedImage(img.getWidth(None), img.getHeight(None),
                            BufferedImage.TYPE_BYTE_GRAY)
         g = bi.createGraphics()
         g.drawImage(img, 0, 0, None)
         g.dispose()
         g = None
         imp = ImagePlus(str(self.layer.getZ()), ByteProcessor(bi))
         FileSaver(imp).saveAsZip(filepath)
         bi.flush()
         bi = None
         imp.flush()
         imp = None
         ip = None
         System.out.println("Saved: " + os.path.split(filepath)[1])
     except:
         import sys
         e = sys.exc_info()
         System.out.println("Error:" + str(e[0]) + "\n" + str(e[1]) + "\n" +
                            str(e[2]))
Exemple #8
0
 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)
Exemple #9
0
def emboss(src, azimuth=135, elevation=30, emboss=False, bh=1):
    '''
    This filter will emboss an image. 
    
    :param src: (*image*) Source image.
    :param azimuth: (*float*) Azimuth of the light source.
    :param elevation: (*float*) Elevation of the light source.
    :param emboss: (*boolean*) Emboss or not.
    :param bh: (*float*) Bump height.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None

    filter = EmbossFilter()
    azimuth = math.radians(azimuth)
    elevation = math.radians(elevation)
    filter.setAzimuth(azimuth)
    filter.setElevation(elevation)
    filter.setEmboss(emboss)
    filter.setBumpHeight(bh)
    dst = BufferedImage(image.getWidth(), image.getHeight(),
                        BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #10
0
    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
Exemple #11
0
def light(src, height=None, shape=None, softness=None, source=None):
    '''
    A filter which produces lighting and embossing effects.
    
    :param src: (*image*) Source image.
    :param height: (*float*) Bump height.
    :param shape: (*int*) Bump shape.
    :param softness: (*float*) Bump softness.
    :param source: (*int*) Bump source.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None

    filter = LightFilter()
    if not height is None:
        filter.setBumpHeight(height)
    if not shape is None:
        filter.setBumpShape(shape)
    if not softness is None:
        filter.setBumpSoftness(softness)
    if not source is None:
        filter.setBumpSource(source)
    dst = BufferedImage(image.getWidth(), image.getHeight(),
                        BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #12
0
def channel_mix(src, b_g=0, r_b=0, g_r=0, to_r=0, to_g=0, to_b=0):
    '''
    A filter which allows the red, green and blue channels of an image to be mixed into each other.
    
    :param src: (*image*) Source image.
    :param b_g: (*float*) Blue and green.
    :param r_b: (*float*) Red and blue.
    :param g_r: (*float*) Green and red.
    :param to_r: (*float*) Mix into red.
    :param to_g: (*float*) Mix into green.
    :param to_b: (*float*) Mix into blue.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None

    filter = ChannelMixFilter()
    filter.setBlueGreen(b_g)
    filter.setRedBlue(r_b)
    filter.setGreenRed(g_r)
    filter.setIntoR(to_r)
    filter.setIntoG(to_g)
    filter.setIntoB(to_b)
    dst = BufferedImage(image.getWidth(), image.getHeight(),
                        BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #13
0
def scale_to_fill(buffered_image):
    raster = buffered_image.getData()
    width = raster.getWidth()
    height = raster.getHeight()
    #Get extreem values from the image
    max_x = 0
    min_x = width
    max_y = 0
    min_y = height
    for x in range(0, width):
        for y in range(0,height):
            color = pixel_has_color(x,y, raster)
            if(color):
                if x > max_x:
                    max_x = x
                if x < min_x:
                    min_x = x
                if y > max_y:
                    max_y = y
                if y < min_y:
                    min_y = y
    #Cut out the part of image containing colored pixels
    sub_image = buffered_image.getSubimage(min_x, min_y, max_x-min_x+1,max_y-min_y+1)
    #Scale the image
    resized_image = BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY)
    g = resized_image.createGraphics()
    g.drawImage(sub_image, 0, 0, width, height, None)
    g.dispose()
    return resized_image
Exemple #14
0
    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
Exemple #15
0
 def setValue(self, value):
     if value == "":
         img = BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)
         g = img.getGraphics()
         g.setColor(Color.RED)
         g.fillOval(2, 2, 10, 10)
         self.setIcon(ImageIcon(img))
     else:
         self.setIcon(value)
Exemple #16
0
 def __init__(self, obj, filename, res, ulx=0, uly=0):
     self.obj = obj
     self.name = ""
     self.img = None
     self.ulx = ulx
     self.uly = uly
     res = res.lower()
     li = res.split("x")
     isOk = True
     try:
         self.width = int(li[0].strip())
         self.height = int(li[1].strip())
     except:
         isOk = False
     if (not isOk) or ((self.width, self.height) not in resolutions):
         print "Illegal resolution:", res
         print "Supported:", VideoRecorder.getSupportedResolutions()
         return
     self.enc = SequenceEncoder(File(File(filename).getAbsolutePath()))
     if str(type(obj)) == "<type 'ch.aplu.turtle.Turtle'>":
         self.name = "Turtle"
         self.traceBuf = obj.getPlayground().getTraceBuffer()
         self.turtleBuf = obj.getPlayground().getTurtleBuffer()
         self.img = BufferedImage(self.width, self.height,
                                  BufferedImage.TYPE_INT_ARGB)
         self.g2D = self.img.createGraphics()
     elif str(type(obj)) == "<class 'gturtle.TurtleFrame'>":
         self.name = "TurtleFrame"
         self.traceBuf = obj.getPlayground().getTraceBuffer()
         self.turtleBuf = obj.getPlayground().getTurtleBuffer()
         self.img = BufferedImage(self.width, self.height,
                                  BufferedImage.TYPE_INT_ARGB)
         self.g2D = self.img.createGraphics()
     elif str(type(obj)) == "<type 'ch.aplu.util.GPanel'>":
         self.name = "GPanel"
         self.img = BufferedImage(self.width, self.height,
                                  BufferedImage.TYPE_INT_ARGB)
         self.g2D = self.img.createGraphics()
         self.panelBuf = obj.getWindow().getBufferedImage()
     elif str(type(obj)) == "<type 'ch.aplu.jgamegrid.GameGrid'>":
         self.name = "GameGrid"
         self.img = BufferedImage(self.width, self.height,
                                  BufferedImage.TYPE_INT_ARGB)
         self.g2D = self.img.createGraphics()
Exemple #17
0
 def getIcon(self):
     """Set the layer icon.
     """
     if self.iconf is not None:
         return self.iconf
     else:
         img = BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB)
         g = img.getGraphics()
         g.setColor(Color.RED)
         g.fillOval(2, 2, 10, 10)
         return ImageIcon(img)
Exemple #18
0
    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)
Exemple #19
0
 def image(self):
     w = self.getWidth()
     h = self.getHeight()
     non_black_withe_image = BufferedImage(w, h,
                                           BufferedImage.TYPE_INT_ARGB)
     self.paint(non_black_withe_image.getGraphics())
     raster = non_black_withe_image.getRaster()
     bi = BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY)
     write_raster = bi.getRaster()
     c = array.zeros('i', 4)
     on = wc = array.zeros('i', 1)
     off = array.zeros('i', 1)
     off[0] = 1
     for x in range(w):
         for y in range(h):
             c = raster.getPixel(x, y, c)
             if sum(c) != 1020:
                 write_raster.setPixel(x, y, on)
             else:
                 write_raster.setPixel(x, y, off)
     return bi
Exemple #20
0
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 snapshot(frame, box):
    bi = BufferedImage(box.width, box.height, BufferedImage.TYPE_INT_RGB)
    g = bi.createGraphics()
    g.translate(-box.x, -box.y)
    #all black! # frame.paintAll(g)
    #only swing components! # frame.paint(g)
    #only swing components! # frame.update(g)
    #together, also only swing and with errors
    ##frame.update(g)
    ##frame.paint(g)
    # locks the entire graphics machinery # frame.printAll(g)
    # Finally, the right one:
    SwingUtilities.invokeAndWait(PrintAll(frame, g))
    return bi
Exemple #22
0
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 find_shape_sizes(self, shape):
        shapeSizeInDocument = shape.getShapeRenderer().getSizeInPoints()
        width = shapeSizeInDocument.x  # The width of the shape.
        height = shapeSizeInDocument.y  # The height of the shape.
        shapeRenderedSize = shape.getShapeRenderer().getSizeInPixels(1.0, 96.0)

        image = BufferedImage(shapeRenderedSize.width,
                              shapeRenderedSize.height,
                              BufferedImage.TYPE_INT_RGB)

        gr = image.getGraphics()

        # Render shape onto the graphics object using the RenderToScale or RenderToSize methods of ShapeRenderer class.

        gr.dispose()
Exemple #24
0
def gray_scale(src):
    '''
    A filter which converts an image to grayscale using the NTSC brightness calculation.
    
    :param src: (*image*) Source image.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None
            
    filter = GrayscaleFilter()
    dst = BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #25
0
def gray(src):
    '''
    A filter which 'grays out' an image by averaging each pixel with white.
    
    :param src: (*image*) Source image.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None
            
    filter = GrayFilter()
    dst = BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #26
0
def sharpen(src):
    '''
    A filter which performs a simple 3x3 sharpening operation.
    
    :param src: (*image*) Source image.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None
        
    filter = SharpenFilter()  
    dst = BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #27
0
def solarize(src):
    '''
    A filter which solarizes an image.
    
    :param src: (*image*) Source image.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None
            
    filter = SolarizeFilter()
    dst = BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #28
0
def invert(src):
    '''
    A filter which inverts the RGB channels of an image.
    
    :param src: (*image*) Source image.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None
            
    filter = InvertFilter()
    dst = BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #29
0
def invert_alpha(src):
    '''
    A Filter to invert the alpha channel of an image.
    
    :param src: (*image*) Source image.
    
    :returns: Destination image.
    '''
    image = __getimage(src)
    if image is None:
        return None
            
    filter = InvertAlphaFilter()
    dst = BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB)
    filter.filter(image, dst)
    return __getreturn(src, dst)
Exemple #30
0
	def run(self):
		System.out.println("run")
		# zero-pad up to 10 digits
		bi = None
		try:
			title = str(self.i)
			while len(title) < 10:
				title = '0' + title
			bi = BufferedImage(self.bounds.width, self.bounds.height, BufferedImage.TYPE_INT_RGB)
			g = bi.createGraphics()
			g.drawImage(self.borders, 0, 0, None)
			g.drawImage(self.img, self.insets.left, self.insets.top, None)
			FileSaver(ImagePlus(title, ColorProcessor(bi))).saveAsTiff(self.dir + title + '.tif')
		except Exception, e:
			print e
			e.printStackTrace()