Ejemplo n.º 1
0
    private void paintToImage(
        final BufferedImage img, final int x, final int y, final int width, final int height) {
      // clear the prior image
      Graphics2D imgG = (Graphics2D) img.getGraphics();
      imgG.setComposite(AlphaComposite.Clear);
      imgG.setColor(Color.black);
      imgG.fillRect(0, 0, width + blur * 2, height + blur * 2);

      final int adjX = (int) (x + blur + offsetX + (insets.left * distance));
      final int adjY = (int) (y + blur + offsetY + (insets.top * distance));
      final int adjW = (int) (width - (insets.left + insets.right) * distance);
      final int adjH = (int) (height - (insets.top + insets.bottom) * distance);

      // let the delegate paint whatever they want to be blurred
      imgG.setComposite(AlphaComposite.DstAtop);
      if (prePainter != null) prePainter.paint(imgG, adjX, adjY, adjW, adjH);
      imgG.dispose();

      // blur the prior image back into the same pixels
      imgG = (Graphics2D) img.getGraphics();
      imgG.setComposite(AlphaComposite.DstAtop);
      imgG.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
      imgG.setRenderingHint(
          RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
      imgG.drawImage(img, blurOp, 0, 0);

      if (postPainter != null) postPainter.paint(imgG, adjX, adjY, adjW, adjH);
      imgG.dispose();
    }
Ejemplo n.º 2
0
 public BufferedImage filter(BufferedImage src, BufferedImage dst) {
   icentreX = src.getWidth() * centreX;
   icentreY = src.getHeight() * centreY;
   if (radius == 0) radius = Math.min(icentreX, icentreY);
   radius2 = radius * radius;
   return super.filter(src, dst);
 }
Ejemplo n.º 3
0
  private <T> T scaleImageUsingAffineTransformation(final BufferedImage bufferedImage, T target) {
    BufferedImage destinationImage = generateDestinationImage();
    Graphics2D graphics2D = destinationImage.createGraphics();
    AffineTransform transformation =
        AffineTransform.getScaleInstance(
            ((double) getQualifiedWidth() / bufferedImage.getWidth()),
            ((double) getQualifiedHeight() / bufferedImage.getHeight()));
    graphics2D.drawRenderedImage(bufferedImage, transformation);
    graphics2D.addRenderingHints(retrieveRenderingHints());
    try {
      if (target instanceof File) {
        LOGGER.info(String.format(M_TARGET_TYPE_OF, "File"));
        ImageIO.write(destinationImage, imageType.toString(), (File) target);
      } else if (target instanceof ImageOutputStream) {
        LOGGER.info(String.format(M_TARGET_TYPE_OF, "ImageOutputStream"));
        ImageIO.write(destinationImage, imageType.toString(), (ImageOutputStream) target);
      } else if (target instanceof OutputStream) {
        LOGGER.info(String.format(M_TARGET_TYPE_OF, "OutputStream"));
        ImageIO.write(destinationImage, imageType.toString(), (OutputStream) target);
      } else {
        target = null;
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    return target;
  }
Ejemplo n.º 4
0
 private static BufferedImage makeBufferedImage(Icon icon, int w, int h) {
   BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
   Graphics2D g = image.createGraphics();
   icon.paintIcon(null, g, (w - icon.getIconWidth()) / 2, (h - icon.getIconWidth()) / 2);
   g.dispose();
   return image;
 }
 /**
  * Adds next GIF frame. The frame is not written immediately, but is actually deferred until the
  * next frame is received so that timing data can be inserted. Invoking <code>finish()</code>
  * flushes all frames. If <code>setSize</code> was not invoked, the size of the first image is
  * used for all subsequent frames.
  *
  * @param im BufferedImage containing frame to write.
  * @throws IOException if there was an IOException writing the GIF data
  * @throws IllegalArgumentException if this encoder has not been started
  */
 public void addFrame(BufferedImage im) throws IOException {
   if (!started) {
     throw new IllegalStateException("AnimatedGifEncoder not started");
   }
   if (!sizeSet) {
     // use first frame's size
     setSize(im.getWidth(), im.getHeight());
   }
   image = im;
   getImagePixels(); // convert to correct format if necessary
   analyzePixels(); // build color table & map pixels
   if (firstFrame) {
     writeLSD(); // logical screen descriptior
     writePalette(); // global color table
     if (repeat >= 0) {
       // use NS app extension to indicate reps
       writeNetscapeExt();
     }
   }
   writeGraphicCtrlExt(); // write graphic control extension
   writeImageDesc(); // image descriptor
   if (!firstFrame) {
     writePalette(); // local color table
   }
   writePixels(); // encode and write pixel data
   firstFrame = false;
 }
Ejemplo n.º 6
0
  /** paint the canvas into a image file of given width and height */
  public void writeToImage(String s, int w, int h) {
    String ext;
    File f;
    try {
      ext = s.substring(s.lastIndexOf(".") + 1);
      f = new File(s);
    } catch (Exception e) {
      System.out.println(e);
      return;
    }
    if (!ext.equals("jpg") && !ext.equals("png")) {
      System.out.println("Cannot write to file: Illegal extension " + ext);
      return;
    }
    boolean opq = true;
    if (theOpaque != null) opq = theOpaque;

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.setBackground(Color.white);
    g2.setPaint(Color.black);
    g2.setStroke(new BasicStroke(1));
    g2.setRenderingHint(
        RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    doBuffer(g2, true, new Rectangle(0, 0, w, h));
    try {
      ImageIO.write(image, ext, f);
    } catch (Exception e) {
      System.out.println(e);
    }
  }
 protected void computeGeometry() {
   pictHalfWidth = Width.getInt() / 2;
   pictWidth = pictHalfWidth + pictHalfWidth - 1;
   pictHeight = Height.getInt();
   xLoc = -pictHalfWidth;
   yLoc = -pictHeight / 2;
   setFramesPerCycle(pictWidth - 1);
   setFrameIncrement(FrameIncrement.getInt());
   // System.out.println("width = " + pictWidth);
   // System.out.println("    x = " + xLoc);
   // System.out.println("    y = " + yLoc);
   PxlColor[] ramp = AColor.getPxlColor().sinusoidalRampTo(BColor.getPxlColor(), pictHalfWidth);
   // System.out.println("w=" + (4*pictHalfWidth-1) + ", h=" + pictHeight);
   int ibWidth = 4 * pictHalfWidth - 1;
   if ((imageBuffer == null)
       || (imageBuffer.getWidth() != ibWidth)
       || (imageBuffer.getHeight() != pictHeight)) {
     imageBuffer = new BufferedImage(ibWidth, pictHeight, BufferedImage.TYPE_INT_RGB);
   }
   Graphics g = imageBuffer.getGraphics();
   for (int x = 0; x < pictHalfWidth; x++) {
     g.setColor(ramp[x].dev());
     g.drawLine(x, 0, x, pictHeight - 1);
     if (x < (pictHalfWidth - 1))
       g.drawLine(pictWidth - x - 1, 0, pictWidth - x - 1, pictHeight - 1);
     if (x > 0) g.drawLine(pictWidth + x - 1, 0, pictWidth + x - 1, pictHeight - 1);
     if ((x > 0) && (x < (pictHalfWidth - 1)))
       g.drawLine(4 * pictHalfWidth - 4 - x, 0, 4 * pictHalfWidth - 4 - x, pictHeight - 1);
   }
   g.dispose();
   BitMapElement p = (BitMapElement) getDisplayElement(pictElement);
   p.setImage(imageBuffer);
   p.setLocation(xLoc, yLoc);
   p.setClipRect(xLoc, yLoc, pictWidth, pictHeight);
 }
Ejemplo n.º 8
0
  public BufferedImage createCrystalCase(Image cover) {
    BufferedImage crystal =
        new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = crystal.createGraphics();
    g2.setRenderingHint(
        RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    int width = cover.getWidth(null);
    int height = cover.getHeight(null);

    float scale;

    if (width > height) {
      scale = (float) IMAGE_WIDTH / (float) width;
    } else {
      scale = (float) IMAGE_HEIGHT / (float) height;
    }

    int scaledWidth = (int) ((float) width * scale);
    int scaledHeight = (int) ((float) height * scale);

    int x = (IMAGE_WIDTH - scaledWidth) / 2;
    int y = (IMAGE_HEIGHT - scaledHeight) / 2;

    g2.drawImage(cover, x, y, scaledWidth, scaledHeight, null);

    g2.dispose();

    return crystal;
  }
Ejemplo n.º 9
0
  @Override
  protected void paintComponent(Graphics graphics) {
    // Fill in the background:
    Graphics2D g = (Graphics2D) graphics;
    Shape clip = g.getClip();
    g.setColor(LightZoneSkin.Colors.NeutralGray);
    g.fill(clip);

    if (preview == null) {
      PlanarImage image = currentImage.get();
      if (image == null) {
        engine.update(null, false);
      } else if (visibleRect != null && getHeight() > 1 && getWidth() > 1) {
        preview = cropScaleGrayscale(visibleRect, image);
      }
    }
    if (preview != null) {
      int dx, dy;
      AffineTransform transform = new AffineTransform();
      if (getSize().width > preview.getWidth()) dx = (getSize().width - preview.getWidth()) / 2;
      else dx = 0;
      if (getSize().height > preview.getHeight()) dy = (getSize().height - preview.getHeight()) / 2;
      else dy = 0;
      transform.setToTranslation(dx, dy);
      try {
        g.drawRenderedImage(preview, transform);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
Ejemplo n.º 10
0
  public static void main(String[] args) {
    int x = 500, y = 80;
    DrawingKit dk = new DrawingKit("Daffodils", 800, 800);
    BufferedImage pict = dk.loadPicture("daffodils.jpg");

    // get pixel value at location (500, 80)
    int encodedPixelColor = pict.getRGB(x, y);
    Color pixelColor = new Color(encodedPixelColor);
    System.out.println(pixelColor);
    int red = pixelColor.getRed();
    int green = pixelColor.getGreen();
    int blue = pixelColor.getBlue();
    // change the color of the pixel to be pure red
    red = 255;
    green = 0;
    blue = 0;

    // update the pixel color in picture
    Color newPixelColor = new Color(red, green, blue);
    int newRgbvalue = newPixelColor.getRGB();
    pict.setRGB(x, y, newRgbvalue);
    // display the approximate location of the pixel
    dk.drawPicture(pict, 0, 0);
    BasicStroke s = new BasicStroke(3);
    dk.setStroke(s);
    Ellipse2D.Float e = new Ellipse2D.Float(x - 3, y - 3, 8, 8);
    dk.draw(e);
    dk.drawString("(600, 150)", x - 3, y - 5);
  }
Ejemplo n.º 11
0
 /**
  * Appends a frame to the current video.
  *
  * @param image the image to append
  * @return true if image successfully appended
  */
 protected boolean append(Image image) {
   BufferedImage bi;
   if (image instanceof BufferedImage) {
     bi = (BufferedImage) image;
   } else {
     bi = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);
     Graphics2D g = bi.createGraphics();
     g.drawImage(image, 0, 0, null);
   }
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   try {
     if (!editing) {
       videoMedia.beginEdits();
       editing = true;
     }
     ImageIO.write(bi, "png", out); // $NON-NLS-1$
     QTHandle handle = new QTHandle(out.toByteArray());
     DataRef dataRef = new DataRef(handle, kDataRefFileExtensionTag, "png"); // $NON-NLS-1$
     GraphicsImporter importer = new GraphicsImporter(dataRef);
     ImageDescription description = importer.getImageDescription();
     int duration = (int) (frameDuration * 0.6);
     videoMedia.addSample(
         handle,
         0, // data offset
         handle.getSize(),
         duration,
         description,
         1, // number of samples
         0); // key frame??
   } catch (Exception ex) {
     ex.printStackTrace();
     return false;
   }
   return true;
 }
  public static void saveJPG(Image img, String s) {
    BufferedImage bi =
        new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = bi.createGraphics();
    g2.drawImage(img, null, null);

    FileOutputStream out = null;
    try {
      out = new FileOutputStream(s);
    } catch (java.io.FileNotFoundException io) {
      System.out.println("File Not Found");
    }

    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
    JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
    param.setQuality(0.5f, false);
    encoder.setJPEGEncodeParam(param);

    try {
      encoder.encode(bi);
      out.close();
    } catch (java.io.IOException io) {
      System.out.println("IOException");
    }
  }
Ejemplo n.º 13
0
  private void gameRender() {
    if (dbImage == null) {
      dbImage = createImage(PWIDTH, PHEIGHT);
      if (dbImage == null) {
        System.out.println("dbImage is null");
        return;
      } else dbg = dbImage.getGraphics();
    }

    // draw a white background
    dbg.setColor(Color.white);
    dbg.fillRect(0, 0, PWIDTH, PHEIGHT);

    // draw the game elements: order is important
    ribsMan.display(dbg); // the background ribbons
    bricksMan.display(dbg); // the bricks
    jack.drawSprite(dbg); // the sprites
    fireball.drawSprite(dbg);

    if (showExplosion) // draw the explosion (in front of jack)
    dbg.drawImage(explosionPlayer.getCurrentImage(), xExpl, yExpl, null);

    reportStats(dbg);

    if (gameOver) gameOverMessage(dbg);

    if (showHelp) // draw the help at the very front (if switched on)
    dbg.drawImage(
          helpIm, (PWIDTH - helpIm.getWidth()) / 2, (PHEIGHT - helpIm.getHeight()) / 2, null);
  } // end of gameRender()
Ejemplo n.º 14
0
  /**
   * Returns the specified image as icon.
   *
   * @param name name of icon
   * @return icon
   */
  public static ImageIcon icon(final String name) {
    ImageIcon ii = ICONS.get(name);
    if (ii != null) return ii;

    Image img;
    if (GUIConstants.scale > 1) {
      // choose large image or none
      final URL url =
          GUIConstants.large() ? BaseXImages.class.getResource("/img/" + name + "_32.png") : null;

      if (url == null) {
        // resize low-res image if no hi-res image exists
        img = get(url(name));
        final int w = (int) (img.getWidth(null) * GUIConstants.scale);
        final int h = (int) (img.getHeight(null) * GUIConstants.scale);
        final BufferedImage tmp = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        final Graphics2D g2 = tmp.createGraphics();
        g2.setRenderingHint(
            RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g2.drawImage(img, 0, 0, w, h, null);
        g2.dispose();
        img = tmp;
      } else {
        img = get(url);
      }
    } else {
      img = get(name);
    }
    ii = new ImageIcon(img);
    ICONS.put(name, ii);
    return ii;
  }
Ejemplo n.º 15
0
 /**
  * Convert a source to a BufferedImage. Source supported:
  * File,BufferedImage,InputStream,URL,ImageInputStream, byte[]
  *
  * @param imageType the ImageType to use
  * @param source source to generate BufferedImage from
  * @return Enhanced BufferedImage
  * @throws NullPointerException _
  * @throws IOException _
  * @throws UnsupportedOperationException throws this is the source is of unsupported type
  */
 public static <T> BufferedImage convertImageType(final ImageType imageType, final T source)
     throws NullPointerException, IOException, UnsupportedOperationException {
   if (verifyNotNull(imageType, source)) {
     BufferedImage target = null;
     if (source instanceof File) {
       target = convert(ImageIO.read((File) source), imageType);
     } else if (source instanceof BufferedImage) {
       target = convert((BufferedImage) source, imageType);
     } else if (source instanceof InputStream) {
       target = convert(ImageIO.read((InputStream) source), imageType);
     } else if (source instanceof URL) {
       target = convert(ImageIO.read((URL) source), imageType);
     } else if (source instanceof ImageInputStream) {
       target = convert(ImageIO.read((ImageInputStream) source), imageType);
     } else if (source instanceof byte[]) {
       final InputStream streamOfInput = new ByteArrayInputStream((byte[]) source);
       target = convert(ImageIO.read(streamOfInput), imageType);
     } else {
       throw new UnsupportedOperationException("%s is not supported. Read JavaDoc.");
     }
     if (verifyNotNull(target)) {
       LOGGER.info(
           String.format(
               "Returning requested converted object<%s> as target", target.getClass().getName()));
       return target;
     }
     throw new NullPointerException("Return value was null.");
   }
   throw new NullPointerException("Nilled param detected. Please verify your params!");
 }
 /**
  * A convenience method for getting ARGB pixels from an image. This tries to avoid the performance
  * penalty of BufferedImage.getRGB unmanaging the image.
  *
  * @param image a BufferedImage object
  * @param x the left edge of the pixel block
  * @param y the right edge of the pixel block
  * @param width the width of the pixel arry
  * @param height the height of the pixel arry
  * @param pixels the array to hold the returned pixels. May be null.
  * @return the pixels
  * @see #setRGB
  */
 public int[] getRGB(BufferedImage image, int x, int y, int width, int height, int[] pixels) {
   int type = image.getType();
   if (type == BufferedImage.TYPE_INT_ARGB || type == BufferedImage.TYPE_INT_RGB) {
     return (int[]) image.getRaster().getDataElements(x, y, width, height, pixels);
   }
   return image.getRGB(x, y, width, height, pixels, 0, width);
 }
Ejemplo n.º 17
0
  /**
   * Adds next GIF frame. The frame is not written immediately, but is actually deferred until the
   * next frame is received so that timing data can be inserted. Invoking <code>finish()</code>
   * flushes all frames. If <code>setSize</code> was not invoked, the size of the first image is
   * used for all subsequent frames.
   *
   * @param im BufferedImage containing frame to write.
   * @return true if successful.
   */
  public boolean addFrame(BufferedImage im) {
    if ((im == null) || !started) {
      return false;
    }
    boolean ok = true;
    try {
      if (!sizeSet) {
        // use first frame's size
        setSize(im.getWidth(), im.getHeight());
      }
      image = im;
      getImagePixels(); // convert to correct format if necessary
      analyzePixels(); // build color table & map pixels
      if (firstFrame) {
        writeLSD(); // logical screen descriptior
        writePalette(); // global color table
        if (repeat >= 0) {
          // use NS app extension to indicate reps
          writeNetscapeExt();
        }
      }
      writeGraphicCtrlExt(); // write graphic control extension
      writeImageDesc(); // image descriptor
      if (!firstFrame) {
        writePalette(); // local color table
      }
      writePixels(); // encode and write pixel data
      firstFrame = false;
    } catch (IOException e) {
      ok = false;
    }

    return ok;
  }
  /** Creates a new instance of IDEJRManFramebufferImpl */
  public IDEJRManFramebufferImpl(String name, BufferedImage image) {
    super("JRMan rendered: " + name, true, true, true, true);
    this.name = name;

    save.setEnabled(false);

    imagePanel.setImage(image);
    imagePanel.addToolbarAction(save);
    if (image.getType() == BufferedImage.TYPE_INT_ARGB
        || image.getType() == BufferedImage.TYPE_INT_ARGB_PRE) {
      imagePanel.setShowTransparencyPattern(true);
    }

    getRootPane().setDoubleBuffered(false);
    getContentPane().add(imagePanel);
    pack();

    ImageResource images = ImageResource.getInstance();

    // set the frame icon
    setFrameIcon(images.getJrMan());

    // add this to the IDE desktop
    MainMenuEventHandlers.getInstance(null)
        .getIdeInstance()
        .getWorkspaceDesktop()
        .addInternalFrame(this, true);
  }
Ejemplo n.º 19
0
  private void stuffWithLeastSignificantBit(BufferedImage image, byte[] message) {
    int[] pixelValues = getImagePixels(image);
    if (message.length * 8 > pixelValues.length * 3) {
      System.out.printf("Cannot stuff message in least significant bit\n");
    }

    int messageIndex = 0;
    int currentByteOffset = -1;

    pixls:
    for (int i = 0; i < pixelValues.length; i++) {
      for (int offset = 0; offset < 17; offset += 8) {
        currentByteOffset++;
        if (currentByteOffset > 7) {
          currentByteOffset = 0;
          messageIndex++;
        }
        if (messageIndex >= message.length) break pixls;
        int bitToEncode = (message[messageIndex] >> currentByteOffset) & 1;
        // color = (byte) ((color & 0xfe) | bitToEncode);
        // zero
        pixelValues[i] &= ~(0x1 << offset);
        // fill
        pixelValues[i] |= bitToEncode << offset;
      }
    }

    // put pixel ints back into BufferedImage
    for (int i = 0; i < pixelValues.length; i++) {
      int x = i % image.getWidth();
      int y = i / image.getWidth();
      image.setRGB(x, y, pixelValues[i]);
    }
  }
 public SimpleWhiteboardPanel(int width, int height) {
   this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   Graphics g = this.image.getGraphics();
   g.setColor(Color.WHITE);
   g.fillRect(0, 0, image.getWidth(), image.getHeight());
   this.setFocusable(true);
 }
Ejemplo n.º 21
0
    // This is used to create a CImage from a Image
    public CImage createFromImage(final Image image) {
      if (image == null) return null;

      MediaTracker mt = new MediaTracker(new Label());
      final int id = 0;
      mt.addImage(image, id);

      try {
        mt.waitForID(id);
      } catch (InterruptedException e) {
      }

      if (mt.isErrorID(id)) {
        return null;
      }

      int w = image.getWidth(null);
      int h = image.getHeight(null);
      BufferedImage bimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB_PRE);
      Graphics2D g2 = bimg.createGraphics();
      g2.setComposite(AlphaComposite.Src);
      g2.drawImage(image, 0, 0, null);
      g2.dispose();
      int[] buffer = ((DataBufferInt) bimg.getRaster().getDataBuffer()).getData();
      return new CImage(nativeCreateNSImageFromArray(buffer, w, h));
    }
Ejemplo n.º 22
0
  public void generarFondo(Component componente) {
    boolean dibujarFondo = false;
    Rectangle med = this.getBounds();
    Rectangle areaDibujo = this.getBounds();
    BufferedImage tmp;
    GraphicsConfiguration gc =
        GraphicsEnvironment.getLocalGraphicsEnvironment()
            .getDefaultScreenDevice()
            .getDefaultConfiguration();

    if (Principal.fondoBlur) {
      dibujarFondo = true;
    }
    if (dibujarFondo) {
      JRootPane root = SwingUtilities.getRootPane(this);
      blurBuffer = GraphicsUtilities.createCompatibleImage(Principal.sysAncho, Principal.sysAlto);
      Graphics2D g2 = blurBuffer.createGraphics();
      g2.setClip(med);
      blurBuffer = blurBuffer.getSubimage(med.x, med.y, med.width, med.height);
      ((Escritorio) Principal.getEscritorio()).getFrameEscritorio().paint(g2);
      g2.dispose();
      backBuffer = blurBuffer;
      // blurBuffer = toGrayScale(blurBuffer);
      blurBuffer = GraphicsUtilities.createThumbnailFast(blurBuffer, getWidth() / 2);
      blurBuffer = new GaussianBlurFilter(4).filter(blurBuffer, null);
      g2 = (Graphics2D) blurBuffer.getGraphics();
      g2.setColor(new Color(0, 0, 0, 195));
      g2.fillRect(0, 0, Principal.sysAncho, Principal.sysAlto);
      listo = true;
    }
  }
Ejemplo n.º 23
0
  /**
   * Save onscreen image to file - suffix must be png, jpg, or gif.
   *
   * @param filename the name of the file with one of the required suffixes
   */
  public static void save(String filename) {
    File file = new File(filename);
    String suffix = filename.substring(filename.lastIndexOf('.') + 1);

    // png files
    if (suffix.toLowerCase().equals("png")) {
      try {
        ImageIO.write(onscreenImage, suffix, file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // need to change from ARGB to RGB for jpeg
    // reference: http://archives.java.sun.com/cgi-bin/wa?A2=ind0404&L=java2d-interest&D=0&P=2727
    else if (suffix.toLowerCase().equals("jpg")) {
      WritableRaster raster = onscreenImage.getRaster();
      WritableRaster newRaster;
      newRaster = raster.createWritableChild(0, 0, width, height, 0, 0, new int[] {0, 1, 2});
      DirectColorModel cm = (DirectColorModel) onscreenImage.getColorModel();
      DirectColorModel newCM =
          new DirectColorModel(
              cm.getPixelSize(), cm.getRedMask(), cm.getGreenMask(), cm.getBlueMask());
      BufferedImage rgbBuffer = new BufferedImage(newCM, newRaster, false, null);
      try {
        ImageIO.write(rgbBuffer, suffix, file);
      } catch (IOException e) {
        e.printStackTrace();
      }
    } else {
      System.out.println("Invalid image file type: " + suffix);
    }
  }
Ejemplo n.º 24
0
 // buffered images are just better.
 protected static BufferedImage imageToBufferedImage(Image img) {
   BufferedImage bi =
       new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
   Graphics2D g2 = bi.createGraphics();
   g2.drawImage(img, null, null);
   return bi;
 }
  protected void drawPointLegend(
      VPFSymbolAttributes attr, Graphics2D g2, int width, int height, int margin) {
    if (attr.getIconImageSource() == null) return;

    BufferedImage icon = getImage(attr.getIconImageSource());
    if (icon != null) {
      // icon width / height
      int iw = icon.getWidth();
      int ih = icon.getHeight();
      // draw area width / height
      int dw = width - margin * 2;
      int dh = height - margin * 2;
      // draw scale to fit icon inside draw area
      float sx = iw > dw ? (float) dw / iw : 1f; // shrink only
      float sy = ih > dh ? (float) dh / ih : 1f;
      float scale = Math.min(sx, sy);
      iw = (int) ((float) iw * scale);
      ih = (int) ((float) ih * scale);
      // Center image and draw
      int x1 = iw < dw ? margin + (dw - iw) / 2 : margin;
      int y1 = ih < dh ? margin + (dh - ih) / 2 : margin;
      g2.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      g2.drawImage(icon, x1, y1, iw, ih, null);
    }
  }
Ejemplo n.º 26
0
  public void scaleImage(
      Image image, int p_width, int p_height, boolean keepaspect) /*throws Exception*/ {

    int thumbWidth = p_width;
    int thumbHeight = p_height;

    // Make sure the aspect ratio is maintained, so the image is not skewed
    if (keepaspect) {
      double thumbRatio = (double) thumbWidth / (double) thumbHeight;
      int imageWidth = image.getWidth(null);
      int imageHeight = image.getHeight(null);
      double imageRatio = (double) imageWidth / (double) imageHeight;
      if (thumbRatio < imageRatio) {
        thumbHeight = (int) (thumbWidth / imageRatio);
      } else {
        thumbWidth = (int) (thumbHeight * imageRatio);
      }
    }

    // Draw the scaled image
    BufferedImage thumbImage =
        new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D graphics2D = thumbImage.createGraphics();
    graphics2D.setRenderingHint(
        RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
    this.img = thumbImage;
  }
 public Image getScreenshot() {
   BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
   Graphics g = image.getGraphics();
   paint(g);
   g.dispose();
   return image;
 }
Ejemplo n.º 28
0
    public synchronized void paint(Graphics g) {
      if (needToStartThread) {
        totalDrawTime = 0;
        counter = 0;
        needToStartThread = false;
        startThread(beginAngle, endAngle);
        if (firstImage == null) {
          firstImage = createImageFromComponent(component1);
        }
        if (secondImage == null) {
          secondImage = createImageFromComponent(component2);
        }
      }
      if (firstImage == null || secondImage == null) return;
      Graphics2D g2d = (Graphics2D) g;
      int ww = firstImage.getWidth();
      int hh = firstImage.getHeight();
      {
        BufferedImage currImage = null;
        int[] currPixels = null;
        int w = firstImage.getWidth();
        int offset = (int) (w * angle / 180);
        if (offset < 0) offset = 0;
        if (offset > w) offset = w;

        long beforeDraw = System.currentTimeMillis();
        g2d.drawImage(firstImage, null, 0, 0);
        g2d.drawImage(secondImage, null, w - offset, 0);
        totalDrawTime += (System.currentTimeMillis() - beforeDraw);
        counter++;
      }
    }
Ejemplo n.º 29
0
  public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    if (dst == null) dst = createCompatibleDestImage(src, null);

    int width = src.getWidth();
    int height = src.getHeight();
    int numScratches = (int) (density * width * height / 100);
    ArrayList<Line2D> lines = new ArrayList<Line2D>();
    {
      float l = length * width;
      Random random = new Random(seed);
      Graphics2D g = dst.createGraphics();
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g.setColor(new Color(color));
      g.setStroke(new BasicStroke(this.width));
      for (int i = 0; i < numScratches; i++) {
        float x = width * random.nextFloat();
        float y = height * random.nextFloat();
        float a = angle + ImageMath.TWO_PI * (angleVariation * (random.nextFloat() - 0.5f));
        float s = (float) Math.sin(a) * l;
        float c = (float) Math.cos(a) * l;
        float x1 = x - c;
        float y1 = y - s;
        float x2 = x + c;
        float y2 = y + s;
        g.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
        lines.add(new Line2D.Float(x1, y1, x2, y2));
      }
      g.dispose();
    }

    if (false) {
      //		int[] inPixels = getRGB( src, 0, 0, width, height, null );
      int[] inPixels = new int[width * height];
      int index = 0;
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          float sx = x, sy = y;
          for (int i = 0; i < numScratches; i++) {
            Line2D.Float l = (Line2D.Float) lines.get(i);
            float dot = (l.x2 - l.x1) * (sx - l.x1) + (l.y2 - l.y1) * (sy - l.y1);
            if (dot > 0) inPixels[index] |= (1 << i);
          }
          index++;
        }
      }

      Colormap colormap = new LinearColormap();
      index = 0;
      for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
          float f = (float) (inPixels[index] & 0x7fffffff) / 0x7fffffff;
          inPixels[index] = colormap.getColor(f);
          index++;
        }
      }
      setRGB(dst, 0, 0, width, height, inPixels);
    }
    return dst;
  }
Ejemplo n.º 30
0
  public void saveFrametoPNG(String filename) {
    final int frameWidth = _canvas.getWidth();
    final int frameHeight = _canvas.getHeight();
    final ByteBuffer pixelsRGB = Direct.newByteBuffer(frameWidth * frameHeight * 3);
    _canvas.runWithContext(
        new Runnable() {
          public void run() {
            // glPushAttrib(GL_PIXEL_MODE_BIT);
            glReadBuffer(GL_BACK);
            glPixelStorei(GL_PACK_ALIGNMENT, 1);
            glReadPixels(0, 0, frameWidth, frameHeight, GL_RGB, GL_UNSIGNED_BYTE, pixelsRGB);
            // glPopAttrib();
          }
        });
    int[] pixelInts = new int[frameWidth * frameHeight];
    int p = frameWidth * frameHeight * 3;
    int q; // Index into ByteBuffer
    int i = 0; // Index into target int[]
    int w3 = frameWidth * 3; // Number of bytes in each row
    for (int row = 0; row < frameHeight; row++) {
      p -= w3;
      q = p;
      for (int col = 0; col < frameWidth; col++) {
        int iR = pixelsRGB.get(q++);
        int iG = pixelsRGB.get(q++);
        int iB = pixelsRGB.get(q++);
        pixelInts[i++] =
            0xFF000000 | ((iR & 0x000000FF) << 16) | ((iG & 0x000000FF) << 8) | (iB & 0x000000FF);
      }
    }

    // Create a new BufferedImage from the pixeldata.
    BufferedImage bufferedImage =
        new BufferedImage(frameWidth, frameHeight, BufferedImage.TYPE_INT_ARGB);
    bufferedImage.setRGB(0, 0, frameWidth, frameHeight, pixelInts, 0, frameWidth);

    try {
      javax.imageio.ImageIO.write(bufferedImage, "PNG", new File(filename));
    } catch (IOException e) {
      System.out.println("Error: ImageIO.write.");
      e.printStackTrace();
    }

    /* End code taken from: http://www.felixgers.de/teaching/jogl/imagingProg.html */

    /*
     final BufferedImage image = new BufferedImage(
     this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
     Graphics gr = image.getGraphics();
     this.printAll(gr);
     gr.dispose();
    try {
    	ImageIO.write(image, "PNG", new File(filename));
      } catch (IOException e) {
           System.out.println( "Error: ImageIO.write." );
           e.printStackTrace();
      }
    */
  }