Search in sources :

Example 26 with Rectangle

use of java.awt.Rectangle in project processing by processing.

the class QuickTimeWriter method writeFrame.

/**
     * Encodes an image as a video frame and writes it into a video track.
     * <p>
     * Only the video encodings listed below are supported by this method.
     * For other encodings, you have to encode the image by yourself and then
     * call one of the {@code writeSample} methods.
     * <ul>
     * <li>RAW</li>
     * <li>JPG</li>
     * <li>PNG</li>
     * </ul>
     *
     * @param track The track index.
     * @param image The image of the video frame.
     * @param duration The duration of the video frame in media time scale units.
     *
     * @throws IndexOutofBoundsException if the track index is out of bounds.
     * @throws if the duration is less than 1, or if the dimension of the frame
     * does not match the dimension of the video.
     * @throws UnsupportedOperationException if the QuickTimeWriter does not have
     * a built-in encoder for this video format.
     * @throws IOException if writing the sample data failed.
     */
public void writeFrame(int track, BufferedImage image, long duration) throws IOException {
    if (duration <= 0) {
        throw new IllegalArgumentException("Duration must be greater 0.");
    }
    // throws index out of bounds exception if illegal track index
    VideoTrack t = (VideoTrack) tracks.get(track);
    if (t.mediaType != MediaType.VIDEO) {
        throw new IllegalArgumentException("Track " + track + " is not a video track");
    }
    if (t.videoEncoding == null) {
        throw new UnsupportedOperationException("Encoding not supported.");
    }
    ensureStarted();
    // The dimension of the image must match the dimension of the video track
    if (t.videoWidth != image.getWidth() || t.videoHeight != image.getHeight()) {
        throw new IllegalArgumentException("Dimensions of frame[" + tracks.get(track).getSampleCount() + "] (width=" + image.getWidth() + ", height=" + image.getHeight() + ") differs from video dimension (width=" + t.videoWidth + ", height=" + t.videoHeight + ") in track " + track + ".");
    }
    long offset = getRelativeStreamPosition();
    boolean isSync;
    switch(t.videoEncoding) {
        case RAW:
            {
                isSync = true;
                switch(t.videoDepth) {
                    case 8:
                        {
                            if (image.getType() != BufferedImage.TYPE_BYTE_INDEXED) {
                                throw new IllegalArgumentException("BufferedImage type " + image.getType() + " does not match track type " + BufferedImage.TYPE_BYTE_INDEXED + ".");
                            }
                            // Handle sub-image
                            WritableRaster raster = image.getRaster();
                            int sw = raster.getSampleModel().getWidth();
                            //                        int sh = raster.getSampleModel().getHeight();
                            Rectangle r = raster.getBounds();
                            r.x -= raster.getSampleModelTranslateX();
                            r.y -= raster.getSampleModelTranslateY();
                            DataBufferByte buf = (DataBufferByte) raster.getDataBuffer();
                            byte[] bytes = buf.getData();
                            // Write the samples
                            for (int xy = r.x + r.y * sw, ymax = r.x + (r.y + r.height) * sw; xy < ymax; xy += sw) {
                                mdatAtom.getOutputStream().write(bytes, xy, r.width);
                            }
                            break;
                        }
                    case 24:
                        {
                            WritableRaster raster = image.getRaster();
                            // holds a scanline of raw image data with 3 channels of 32 bit data
                            int[] rgb = new int[t.videoWidth * 3];
                            // holds a scanline of raw image data with 3 channels of 8 bit data
                            byte[] bytes = new byte[t.videoWidth * 3];
                            for (int y = 0; y < t.videoHeight; y++) {
                                // Note: Method getPixels is very slow as it does sample conversions for us
                                rgb = raster.getPixels(0, y, t.videoWidth, 1, rgb);
                                for (int k = 0, n = t.videoWidth * 3; k < n; k++) {
                                    bytes[k] = (byte) rgb[k];
                                }
                                mdatAtom.getOutputStream().write(bytes);
                            }
                            break;
                        }
                    default:
                        throw new UnsupportedOperationException("Encoding not supported.");
                }
                break;
            }
        case JPG:
            {
                isSync = true;
                ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/jpeg").next();
                ImageWriteParam iwParam = iw.getDefaultWriteParam();
                iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                iwParam.setCompressionQuality(t.videoQuality);
                MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(mdatAtom.getOutputStream());
                iw.setOutput(imgOut);
                IIOImage img = new IIOImage(image, null, null);
                iw.write(null, img, iwParam);
                iw.dispose();
                break;
            }
        case PNG:
            {
                isSync = true;
                ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/png").next();
                ImageWriteParam iwParam = iw.getDefaultWriteParam();
                // FIXME - Detect number of bits per pixel, ensure that correct value is written into video media header atom.
                // FIXME - Maybe we should quietly enforce 24 bits per pixel
                MemoryCacheImageOutputStream imgOut = new MemoryCacheImageOutputStream(mdatAtom.getOutputStream());
                iw.setOutput(imgOut);
                IIOImage img = new IIOImage(image, null, null);
                iw.write(null, img, iwParam);
                iw.dispose();
                break;
            }
        case RLE:
            {
                isSync = t.previousData == null || t.syncInterval != 0 && t.sampleCount % t.syncInterval == 0;
                // Handle sub-image
                WritableRaster raster = image.getRaster();
                int sw = raster.getSampleModel().getWidth();
                //                int sh = raster.getSampleModel().getHeight();
                Rectangle r = raster.getBounds();
                r.x -= raster.getSampleModelTranslateX();
                r.y -= raster.getSampleModelTranslateY();
                if (t.encoder == null) {
                    t.encoder = new AppleRLEEncoder();
                }
                AppleRLEEncoder enc = t.encoder;
                switch(t.videoDepth) {
                    case 16:
                        {
                            DataBufferUShort buf = (DataBufferUShort) raster.getDataBuffer();
                            short[] data = buf.getData();
                            if (isSync) {
                                enc.writeKey16(mdatAtom.getOutputStream(), data, r.width, r.height, r.x + r.y * sw, sw);
                            } else {
                                // FIXME - We blindly assume that the sub-image of the previous image is the same as the current one
                                enc.writeDelta16(mdatAtom.getOutputStream(), data, (short[]) t.previousData, r.width, r.height, r.x + r.y * sw, sw);
                            }
                            if (t.previousData == null) {
                                t.previousData = new short[data.length];
                            }
                            System.arraycopy(data, 0, t.previousData, 0, data.length);
                            break;
                        }
                    case 24:
                        {
                            DataBufferInt buf = (DataBufferInt) raster.getDataBuffer();
                            int[] data = buf.getData();
                            if (isSync) {
                                enc.writeKey24(mdatAtom.getOutputStream(), data, r.width, r.height, r.x + r.y * sw, sw);
                            } else {
                                // FIXME - We blindly assume that the sub-image of the previous image is the same as the current one
                                enc.writeDelta24(mdatAtom.getOutputStream(), data, (int[]) t.previousData, r.width, r.height, r.x + r.y * sw, sw);
                            }
                            if (t.previousData == null) {
                                t.previousData = new int[data.length];
                            }
                            System.arraycopy(data, 0, t.previousData, 0, data.length);
                            break;
                        }
                    case 32:
                        {
                            DataBufferInt buf = (DataBufferInt) raster.getDataBuffer();
                            int[] data = buf.getData();
                            if (isSync) {
                                enc.writeKey32(mdatAtom.getOutputStream(), data, image.getWidth(), image.getHeight(), 0, image.getWidth());
                            } else {
                                // FIXME - We blindly assume that the sub-image of the previous image is the same as the current one
                                enc.writeDelta32(mdatAtom.getOutputStream(), data, (int[]) t.previousData, image.getWidth(), image.getHeight(), 0, image.getWidth());
                            }
                            if (t.previousData == null) {
                                t.previousData = new int[data.length];
                            }
                            System.arraycopy(data, 0, t.previousData, 0, data.length);
                            break;
                        }
                    default:
                        throw new UnsupportedOperationException("Encoding not supported.");
                }
                break;
            }
        default:
            {
                throw new UnsupportedOperationException("Encoding not supported.");
            }
    }
    long length = getRelativeStreamPosition() - offset;
    t.addSample(new Sample(duration, offset, length), 1, isSync);
}
Also used : Rectangle(java.awt.Rectangle) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) WritableRaster(java.awt.image.WritableRaster) DataBufferUShort(java.awt.image.DataBufferUShort)

Example 27 with Rectangle

use of java.awt.Rectangle in project processing by processing.

the class PSurfaceAWT method getDisplaySpan.

//public void initImage(PGraphics gr, int wide, int high) {
/*
  @Override
  public void initImage(PGraphics graphics) {
    GraphicsConfiguration gc = canvas.getGraphicsConfiguration();
    // If not realized (off-screen, i.e the Color Selector Tool), gc will be null.
    if (gc == null) {
      System.err.println("GraphicsConfiguration null in initImage()");
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
      gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
    }

    // Formerly this was broken into separate versions based on offscreen or
    // not, but we may as well create a compatible image; it won't hurt, right?
    int wide = graphics.width * graphics.pixelFactor;
    int high = graphics.height * graphics.pixelFactor;
    graphics.image = gc.createCompatibleImage(wide, high);
  }
  */
//  @Override
//  public Component getComponent() {
//    return canvas;
//  }
//  @Override
//  public void setSmooth(int level) {
//  }
/*
  private boolean checkRetina() {
    if (PApplet.platform == PConstants.MACOSX) {
      // This should probably be reset each time there's a display change.
      // A 5-minute search didn't turn up any such event in the Java 7 API.
      // Also, should we use the Toolkit associated with the editor window?
      final String javaVendor = System.getProperty("java.vendor");
      if (javaVendor.contains("Oracle")) {
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice device = env.getDefaultScreenDevice();

        try {
          Field field = device.getClass().getDeclaredField("scale");
          if (field != null) {
            field.setAccessible(true);
            Object scale = field.get(device);

            if (scale instanceof Integer && ((Integer)scale).intValue() == 2) {
              return true;
            }
          }
        } catch (Exception ignore) { }
      }
    }
    return false;
  }
  */
/** Get the bounds rectangle for all displays. */
static Rectangle getDisplaySpan() {
    Rectangle bounds = new Rectangle();
    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    for (GraphicsDevice device : environment.getScreenDevices()) {
        for (GraphicsConfiguration config : device.getConfigurations()) {
            Rectangle2D.union(bounds, config.getBounds(), bounds);
        }
    }
    return bounds;
}
Also used : GraphicsDevice(java.awt.GraphicsDevice) Rectangle(java.awt.Rectangle) GraphicsEnvironment(java.awt.GraphicsEnvironment) GraphicsConfiguration(java.awt.GraphicsConfiguration)

Example 28 with Rectangle

use of java.awt.Rectangle in project darkFunction-Editor by darkFunction.

the class SpriteImageController method addNodeToPanel.

private void addNodeToPanel(CustomNode aNode, BufferedImage aImage) {
    if (aNode.isLeaf()) {
        GraphicObject sb = (GraphicObject) aNode.getCustomObject();
        // what we have here is actually a SelectionBox - we need to change it
        // into a SpriteGraphic
        Rectangle r = sb.getRect();
        SpriteGraphic graphic = new SpriteGraphic(aImage, new java.awt.Point(r.x, r.y), r);
        aNode.setCustomObject(graphic);
        int w = aImage.getWidth();
        int h = aImage.getHeight();
        textureWidthField.setText(Integer.toString(w));
        textureHeightField.setText(Integer.toString(h));
        viewPanel.setTextureArea(w, h);
        viewPanel.addGraphic(graphic);
    } else {
        for (int i = 0; i < aNode.getChildCount(); ++i) {
            addNodeToPanel((CustomNode) aNode.getChildAt(i), aImage);
        }
    }
}
Also used : Rectangle(java.awt.Rectangle)

Example 29 with Rectangle

use of java.awt.Rectangle in project darkFunction-Editor by darkFunction.

the class SpriteImageController method addSpriteButtonActionPerformed.

// </editor-fold>//GEN-END:initComponents
private void addSpriteButtonActionPerformed(java.awt.event.ActionEvent evt) {
    //GEN-FIRST:event_addSpriteButtonActionPerformed
    File[] selectedFiles = this.showSetImageChooser();
    if (selectedFiles != null) {
        CustomNode parentNode = (CustomNode) nameTree.getSelectedNodeDir();
        if (parentNode == null)
            parentNode = _lastSelectedDirNode;
        if (parentNode == null)
            parentNode = (CustomNode) nameTree.getModel().getRoot();
        ArrayList<GraphicObject> graphicList = new ArrayList();
        for (int i = 0; i < selectedFiles.length; ++i) {
            try {
                BufferedImage bufferedImage = ImageIO.read(selectedFiles[i]);
                SpriteGraphic graphic = new SpriteGraphic(bufferedImage, new java.awt.Point(0, 0), new Rectangle(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight()));
                graphicList.add(graphic);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Could not import " + selectedFiles[i].getName(), "Image not added", JOptionPane.ERROR_MESSAGE);
            }
        }
        cmdManager.execute(new AddGraphicListToSheetCommand(nameTree, parentNode, viewPanel, graphicList));
    }
}
Also used : ArrayList(java.util.ArrayList) Rectangle(java.awt.Rectangle) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) File(java.io.File)

Example 30 with Rectangle

use of java.awt.Rectangle in project darkFunction-Editor by darkFunction.

the class SpriteImagePanel method drawStack.

@Override
public void drawStack(Graphics g) {
    Rectangle r = convertRectToViewRect(_graphicBounds);
    g.clipRect(r.x, r.y, r.width, r.height);
    super.drawStack(g);
    g.setClip(null);
}
Also used : Rectangle(java.awt.Rectangle)

Aggregations

Rectangle (java.awt.Rectangle)809 Point (java.awt.Point)201 Dimension (java.awt.Dimension)81 BufferedImage (java.awt.image.BufferedImage)68 Graphics2D (java.awt.Graphics2D)65 Color (java.awt.Color)48 Insets (java.awt.Insets)47 ArrayList (java.util.ArrayList)37 Font (java.awt.Font)29 Test (org.junit.Test)28 IOException (java.io.IOException)27 GraphicsConfiguration (java.awt.GraphicsConfiguration)23 Paint (java.awt.Paint)23 GradientPaint (java.awt.GradientPaint)22 FontMetrics (java.awt.FontMetrics)21 Graphics (java.awt.Graphics)21 Rectangle2D (java.awt.geom.Rectangle2D)21 Robot (java.awt.Robot)19 File (java.io.File)19 PeakResult (gdsc.smlm.results.PeakResult)18