Example #1
0
 /**
  * Loads an image from a given URL into a BufferedImage. The image is returned in the format
  * defined by the imageType parameter. Note that this is special cased for JPEG images where
  * loading is performed outside the standard media tracker, for efficiency reasons.
  *
  * @param url URL where the image file is located.
  * @param imageType one of the image type defined in the BufferedImage class.
  * @return loaded image at path or url
  * @see java.awt.image.BufferedImage
  */
 public static synchronized BufferedImage loadBufferedImage(URL url, int imageType) {
   BufferedImage image = null;
   // Special handling for JPEG images to avoid extra processing if possible.
   if (url == null || !url.toString().toLowerCase().endsWith(".jpg")) {
     Image tmpImage = loadImage(url);
     if (tmpImage != null) {
       image = new BufferedImage(tmpImage.getWidth(null), tmpImage.getHeight(null), imageType);
       Graphics2D g = image.createGraphics();
       g.drawImage(tmpImage, 0, 0, null);
       g.dispose();
     }
   } else {
     BufferedImage tmpImage = loadBufferedJPEGImage(url);
     if (tmpImage != null) {
       if (tmpImage.getType() != imageType) {
         log.config("Incompatible JPEG image type: creating new buffer image");
         image = new BufferedImage(tmpImage.getWidth(null), tmpImage.getHeight(null), imageType);
         Graphics2D g = image.createGraphics();
         g.drawImage(tmpImage, 0, 0, null);
         g.dispose();
       } else image = tmpImage;
     }
   }
   return image;
 } //  loadBufferedImage
  private void createImages() {
    int w = 16;
    int h = getPreferredSize().height;
    setTarget(new Rectangle(2, 0, 20, 18));
    Graphics2D g2;

    open = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    g2 = open.createGraphics();
    g2.setPaint(getBackground());
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.fillRect(0, 0, w, h);
    int[] x = {2, w / 2, 14};
    int[] y = {4, 13, 4};
    Polygon p = new Polygon(x, y, 3);
    g2.setPaint(new Color(204, 204, 204));
    g2.fill(p);
    g2.draw(p);
    g2.dispose();

    closed = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    g2 = closed.createGraphics();
    g2.setPaint(getBackground());
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.fillRect(0, 0, w, h);
    x = new int[] {3, 13, 3};
    y = new int[] {4, h / 2, 16};
    p = new Polygon(x, y, 3);
    g2.setPaint(new Color(102, 102, 102));
    g2.fill(p);
    g2.draw(p);
    g2.dispose();
  }
  // Method used to paint shadow around the panel
  @Override
  public void setBounds(int x, int y, int width, int height) {
    super.setBounds(x, y, width, height);

    int w = getWidth() - 68;
    int h = getHeight() - 68;
    int arc = 30;
    int shadowSize = 20;

    shadow = ImagesUtilities.createCompatibleTranslucentImage(w, h);
    Graphics2D g2 = shadow.createGraphics();
    g2.setColor(Color.WHITE);
    g2.fillRoundRect(0, 0, w, h, arc, arc);
    g2.dispose();

    ShadowRenderer renderer = new ShadowRenderer(shadowSize, 0.5f, Color.BLACK);
    shadow = renderer.createShadow(shadow);

    g2 = shadow.createGraphics();
    // The color does not matter, red is used for debugging
    g2.setColor(Color.RED);
    g2.setComposite(AlphaComposite.Clear);
    g2.fillRoundRect(shadowSize, shadowSize, w, h, arc, arc);
    g2.dispose();

    if (shadow != null) {
      int xOffset = (shadow.getWidth() - w) / 2;
      int yOffset = (shadow.getHeight() - h) / 2;
      g2.drawImage(shadow, x - xOffset, y - yOffset, null);
    }
  }
Example #4
0
  public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    if (dst == null) dst = createCompatibleDestImage(src, null);
    BufferedImage tsrc = src;
    float cx = (float) src.getWidth() * centreX;
    float cy = (float) src.getHeight() * centreY;
    float imageRadius = (float) Math.sqrt(cx * cx + cy * cy);
    float translateX = (float) (distance * Math.cos(angle));
    float translateY = (float) (distance * -Math.sin(angle));
    float scale = zoom;
    float rotate = rotation;
    float maxDistance = distance + Math.abs(rotation * imageRadius) + zoom * imageRadius;
    int steps = log2((int) maxDistance);

    translateX /= maxDistance;
    translateY /= maxDistance;
    scale /= maxDistance;
    rotate /= maxDistance;

    if (steps == 0) {
      Graphics2D g = dst.createGraphics();
      g.drawRenderedImage(src, null);
      g.dispose();
      return dst;
    }

    BufferedImage tmp = createCompatibleDestImage(src, null);
    for (int i = 0; i < steps; i++) {
      Graphics2D g = tmp.createGraphics();
      g.drawImage(tsrc, null, null);
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f));

      g.translate(cx + translateX, cy + translateY);
      g.scale(
          1.0001 + scale,
          1.0001
              + scale); // The .0001 works round a bug on Windows where drawImage throws an
                        // ArrayIndexOutofBoundException
      if (rotation != 0) g.rotate(rotate);
      g.translate(-cx, -cy);

      g.drawImage(dst, null, null);
      g.dispose();
      BufferedImage ti = dst;
      dst = tmp;
      tmp = ti;
      tsrc = dst;

      translateX *= 2;
      translateY *= 2;
      scale *= 2;
      rotate *= 2;
    }
    return dst;
  }
  @Override
  protected BufferedImage renderOffscreen() {
    BufferedImage bimage = null;

    if (getOrientation() == SwingConstants.HORIZONTAL) {

      bimage = new BufferedImage(DEFAULT_WIDTH, 10, BufferedImage.TYPE_4BYTE_ABGR);
      Graphics2D g2d = bimage.createGraphics();
      int ncolors = colorMap.getMapSize();
      double distance = colorMap.getMaximumValue() - colorMap.getMinimumValue();

      double start = colorMap.getMinimumValue();

      for (int i = 0; i < ncolors; i++) {
        ColorInterval ci = colorMap.getInterval(i);
        double size = ((ci.getMaximum() - ci.getMinimum()) / distance);
        double xpos = (ci.getMinimum() - start) / distance;

        Rectangle2D rect =
            new Rectangle2D.Double(xpos * DEFAULT_WIDTH, 0, size * DEFAULT_WIDTH, 10);
        float trans = (float) ci.getAlpha();

        AlphaComposite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, trans / 255f);

        g2d.setComposite(comp);
        g2d.setPaint(ci.getColor());
        g2d.fill(rect);
      }
    } else {
      bimage = new BufferedImage(10, DEFAULT_HEIGHT, BufferedImage.TYPE_4BYTE_ABGR);
      int ncolors = colorMap.getMapSize();
      double distance = colorMap.getMaximumValue() - colorMap.getMinimumValue();
      double start = colorMap.getMinimumValue();

      Graphics2D g2d = bimage.createGraphics();
      for (int i = 0; i < ncolors; i++) {
        ColorInterval ci = colorMap.getInterval(i);
        double size = ((ci.getMaximum() - ci.getMinimum()) / distance);
        double ypos = (ci.getMinimum() - start) / distance;

        Rectangle2D rect =
            new Rectangle2D.Double(0, ypos * DEFAULT_HEIGHT, 10, size * DEFAULT_HEIGHT);
        float trans = (float) ci.getAlpha();

        AlphaComposite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, trans / 255f);

        g2d.setComposite(comp);
        g2d.setPaint(ci.getColor());
        g2d.fill(rect);
      }
    }

    cachedImage = bimage;
    return cachedImage;
  }
  private synchronized void renderOutput() {
    switch (calibGUI.getSelectedView()) {
      case 0:
        workImage.createGraphics().drawImage(input, null, null);
        break;

      case 1:
        VisualizeBinaryData.renderBinary(alg.getBinary(), false, workImage);
        break;

      case 2:
        renderClusters();
        break;

      default:
        throw new RuntimeException("Unknown mode");
    }
    Graphics2D g2 = workImage.createGraphics();
    if (foundTarget) {
      if (calibGUI.isShowBound()) {
        //				Polygon2D_I32 bounds =  alg.getFindBound().getBoundPolygon();
        //				drawBounds(g2, bounds);
      }

      if (calibGUI.isShowNumbers()) {
        drawNumbers(g2, alg.getCalibrationPoints(), null, 1);
      }
      calibGUI.setSuccessMessage("FOUND", true);
    } else {
      if (calibGUI.isShowBound()) {
        //				Polygon2D_I32 bounds =  alg.getFindBound().getBoundPolygon();
        //				drawBounds(g2, bounds);
      }

      calibGUI.setSuccessMessage("FAILED", false);
    }

    if (calibGUI.isShowPoints()) {
      List<Point2D_F64> candidates = alg.getCalibrationPoints();
      for (Point2D_F64 c : candidates) {
        VisualizeFeatures.drawPoint(g2, (int) (c.x + 0.5), (int) (c.y + 0.5), 1, Color.RED);
      }
    }

    if (calibGUI.doShowGraph) {
      System.out.println("Maybe I should add this back in with the new detector some how");
    }

    gui.setBufferedImage(workImage);
    gui.setScale(calibGUI.getScale());
    gui.repaint();

    processed = true;
  }
  public static void extractImage(
      String rootDir,
      String scaledDir,
      long subjectId,
      long imageId,
      String fileName,
      int haarMinSize,
      int scaledSize)
      throws IOException {
    FileInputStream input = new FileInputStream(fileName);
    MBFImage image = ImageUtilities.readMBF(input);
    BufferedImage detectedFacesImage = ImageIO.read(new File(fileName));
    // ImageUtils.displayImage(detectedFacesImage);
    FaceDetector<DetectedFace, FImage> fd = new HaarCascadeDetector(haarMinSize);
    List<DetectedFace> faces = fd.detectFaces(Transforms.calculateIntensity(image));
    System.out.println("# Found faces, one per line.");
    System.out.println("# <x>, <y>, <width>, <height>");
    Iterator<DetectedFace> iterator = faces.iterator();
    BufferedImage extractFaceImage = null;
    if (iterator.hasNext()) {
      DetectedFace face = iterator.next();
      Rectangle bounds = face.getBounds();
      //            extractFaceImage = detectedFacesImage.getSubimage((int)bounds.x, (int)bounds.y,
      // (int)bounds.width, (int)bounds.height);
      //            writeImage(extractFaceImage, rootDir, "extracted", subjectId, imageId);

      //            BufferedImage scaledBufferedImage = scale(extractFaceImage, scaledSize);
      //            String scaledFileName = scaledDir + subjectId + "-" + imageId + ".jpg";
      //            System.out.println("scaledFileName = " + scaledFileName);
      //            ImageIO.write(scaledBufferedImage, "jpg", new File(scaledFileName));
      Graphics g = detectedFacesImage.createGraphics();
      g.setColor(Color.GREEN);
      g.drawRect((int) bounds.x, (int) bounds.y, (int) bounds.width, (int) bounds.height);
      System.out.println(bounds.x + ";" + bounds.y + ";" + bounds.width + ";" + bounds.height);
    } else {
      Graphics g = detectedFacesImage.createGraphics();
      g.setColor(Color.GREEN);
      g.drawString("No Image Detected", 20, 20);
    }
    writeImage(detectedFacesImage, rootDir, "detected", subjectId, imageId);
    //
    //        FaceDetector < KEDetectedFace , FImage > fdK = new FKEFaceDetector () ;
    //        List < KEDetectedFace > facesK = fdK.detectFaces ( Transforms.calculateIntensity (
    // image ) ) ;
    //        if (!facesK.isEmpty()) {
    //        	System.out.println("Found face");
    //        	KEDetectedFace detectedKeyFace = facesK.get(0);
    //        	FacialKeypoint[] keypoints = detectedKeyFace.getKeypoints();
    //        	for (FacialKeypoint keypoint: keypoints) {
    //        		System.out.println("keypoint:" + keypoint);
    //        	}
    //        }

  }
Example #8
0
  static BufferedImage getCompositeImage(BufferedImage baseFrame, BufferedImage topFrame) {
    // create top Image
    Graphics2D graphics2D = topFrame.createGraphics();
    graphics2D.drawImage(topFrame, null, 0, 0);
    graphics2D.dispose();

    // draw top on top of baseFrame
    Graphics2D graphics2D1 = baseFrame.createGraphics();
    graphics2D1.drawImage(topFrame, null, 0, 0);
    graphics2D1.dispose();
    return ResourceManager.newFrame(baseFrame);
  }
  /**
   * This function is used to draw very thin white borders over the outer edge of the raster map.
   * It's necessary because the map edge "bleeds" into the adjacent pixels, and we need to cover
   * that.
   *
   * <p>I think this quirky behaviour is possibly an iText bug
   */
  private void addWhiteMapBorder(Image img, Document doc) {

    try {

      Color color = Color.white;
      int borderWidth = 1;

      BufferedImage bufferedTop =
          new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB);
      Graphics2D g1 = bufferedTop.createGraphics();
      g1.setBackground(color);
      g1.clearRect(0, 0, bufferedTop.getWidth(), bufferedTop.getHeight());
      Image top = Image.getInstance(bufferedImage2ByteArray(bufferedTop));
      top.setAbsolutePosition(
          img.getAbsoluteX(),
          img.getAbsoluteY() + img.getScaledHeight() - bufferedTop.getHeight() / 2);

      BufferedImage bufferedBottom =
          new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = bufferedBottom.createGraphics();
      g2.setBackground(color);
      g2.clearRect(0, 0, bufferedBottom.getWidth(), bufferedBottom.getHeight());
      Image bottom = Image.getInstance(bufferedImage2ByteArray(bufferedBottom));
      bottom.setAbsolutePosition(
          img.getAbsoluteX(), img.getAbsoluteY() - bufferedTop.getHeight() / 2);

      BufferedImage bufferedLeft =
          new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g3 = bufferedLeft.createGraphics();
      g3.setBackground(color);
      g3.clearRect(0, 0, bufferedLeft.getWidth(), bufferedLeft.getHeight());
      Image left = Image.getInstance(bufferedImage2ByteArray(bufferedLeft));
      left.setAbsolutePosition(
          img.getAbsoluteX() - bufferedLeft.getWidth() / 2, img.getAbsoluteY());

      BufferedImage bufferedRight =
          new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB);
      Graphics2D g4 = bufferedRight.createGraphics();
      g4.setBackground(color);
      g4.clearRect(0, 0, bufferedRight.getWidth(), bufferedRight.getHeight());
      Image right = Image.getInstance(bufferedImage2ByteArray(bufferedRight));
      right.setAbsolutePosition(
          img.getAbsoluteX() + img.getScaledWidth() - bufferedRight.getWidth() / 2,
          img.getAbsoluteY());

      doc.add(top);
      doc.add(bottom);
      doc.add(left);
      doc.add(right);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #10
0
  public QuadraticForm(String nonRadical, String radical, String denominator) {

    BufferedImage sample = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = sample.createGraphics();

    int fontHeight = g.getFontMetrics().getHeight();

    int fontDip = g.getFontMetrics().getDescent();

    int nonRadicalWidth = g.getFontMetrics().stringWidth(nonRadical + " + ");

    int expInsert = 0;

    if (radical.indexOf("^") > -1) {

      String sub = radical.substring(0, radical.indexOf("^"));

      radical = radical.replace("^2", "  ");

      expInsert = nonRadicalWidth + g.getFontMetrics().stringWidth(sub);
    }

    int radicalWidth = g.getFontMetrics().stringWidth(radical);

    int denominatorWidth = g.getFontMetrics().stringWidth(denominator);

    width = nonRadicalWidth + radicalWidth;

    height = 2 * fontHeight + 2 * fontDip + 5;

    equation = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = equation.createGraphics();

    g2.setColor(Color.BLACK);

    g2.drawString(nonRadical + " ± ", 0, fontHeight);

    g2.drawString(radical, nonRadicalWidth, fontHeight);

    g2.drawString(denominator, (width - denominatorWidth) / 2, fontDip + 2 * fontHeight);

    g2.drawLine(nonRadicalWidth, 3, width, 3);

    g2.drawLine(0, fontHeight + fontDip, width, fontHeight + fontDip);

    g2.setFont(new Font("Times", Font.PLAIN, 8));

    int expHeight = g2.getFontMetrics().getHeight();

    if (expInsert != 0) g2.drawString(2 + "", expInsert, expHeight + 3);
  }
Example #11
0
  static {
    BufferedImage bi = new BufferedImage(10, 10, BufferedImage.TYPE_INT_RGB);
    Graphics2D gi = bi.createGraphics();
    gi.setBackground(Color.white);
    gi.clearRect(0, 0, 10, 10);
    GeneralPath p1 = new GeneralPath();
    p1.moveTo(0, 0);
    p1.lineTo(5, 10);
    p1.lineTo(10, 0);
    p1.closePath();
    gi.setColor(Color.lightGray);
    gi.fill(p1);
    triangles = new TexturePaint(bi, new Rectangle(0, 0, 10, 10));

    bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
    gi = bi.createGraphics();
    gi.setColor(Color.black);
    gi.fillRect(0, 0, 5, 5);
    gi.setColor(Color.gray);
    gi.fillRect(1, 1, 4, 4);
    blacklines = new TexturePaint(bi, new Rectangle(0, 0, 5, 5));

    int w = 30;
    int h = 30;
    bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    gi = bi.createGraphics();
    Color oc = Color.white;
    Color ic = Color.lightGray;
    gi.setPaint(new GradientPaint(0, 0, oc, w * .35f, h * .35f, ic));
    gi.fillRect(0, 0, w / 2, h / 2);
    gi.setPaint(new GradientPaint(w, 0, oc, w * .65f, h * .35f, ic));
    gi.fillRect(w / 2, 0, w / 2, h / 2);
    gi.setPaint(new GradientPaint(0, h, oc, w * .35f, h * .65f, ic));
    gi.fillRect(0, h / 2, w / 2, h / 2);
    gi.setPaint(new GradientPaint(w, h, oc, w * .65f, h * .65f, ic));
    gi.fillRect(w / 2, h / 2, w / 2, h / 2);
    gradient = new TexturePaint(bi, new Rectangle(0, 0, w, h));

    bi = new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB);
    bi.setRGB(0, 0, 0xffffffff);
    bi.setRGB(1, 0, 0xffffffff);
    bi.setRGB(0, 1, 0xffffffff);
    bi.setRGB(1, 1, 0xff0000ff);
    bluedots = new TexturePaint(bi, new Rectangle(0, 0, 2, 2));

    bi = new BufferedImage(2, 2, BufferedImage.TYPE_INT_RGB);
    bi.setRGB(0, 0, 0xffffffff);
    bi.setRGB(1, 0, 0xffffffff);
    bi.setRGB(0, 1, 0xffffffff);
    bi.setRGB(1, 1, 0xff00ff00);
    greendots = new TexturePaint(bi, new Rectangle(0, 0, 2, 2));
  }
Example #12
0
  /**
   * Returns inner shade nine-patch icon.
   *
   * @param shadeWidth shade width
   * @param round corners round
   * @param shadeOpacity shade opacity
   * @return inner shade nine-patch icon
   */
  public static NinePatchIcon createInnerShadeIcon(
      final int shadeWidth, final int round, final float shadeOpacity) {
    // Calculating width for temprorary image
    final int inner = Math.max(shadeWidth, round);
    int width = shadeWidth * 2 + inner * 2;

    // Creating template image
    final BufferedImage bi = new BufferedImage(width, width, BufferedImage.TYPE_INT_ARGB);
    final Graphics2D ig = bi.createGraphics();
    GraphicsUtils.setupAntialias(ig);
    final Area area = new Area(new Rectangle(0, 0, width, width));
    area.exclusiveOr(
        new Area(
            new RoundRectangle2D.Double(
                shadeWidth,
                shadeWidth,
                width - shadeWidth * 2,
                width - shadeWidth * 2,
                round * 2,
                round * 2)));
    ig.setPaint(Color.BLACK);
    ig.fill(area);
    ig.dispose();

    // Creating shade image
    final ShadowFilter sf = new ShadowFilter(shadeWidth, 0, 0, shadeOpacity);
    final BufferedImage shade = sf.filter(bi, null);

    // Clipping shade image
    final Graphics2D g2d = shade.createGraphics();
    GraphicsUtils.setupAntialias(g2d);
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN));
    g2d.setPaint(FlatLafStyleConstants.transparent);
    g2d.fill(area);
    g2d.dispose();

    final BufferedImage croppedShade =
        shade.getSubimage(shadeWidth, shadeWidth, width - shadeWidth * 2, width - shadeWidth * 2);
    width = croppedShade.getWidth();

    // Creating nine-patch icon
    final NinePatchIcon ninePatchIcon = NinePatchIcon.create(croppedShade);
    ninePatchIcon.addHorizontalStretch(0, inner, true);
    ninePatchIcon.addHorizontalStretch(inner + 1, width - inner - 1, false);
    ninePatchIcon.addHorizontalStretch(width - inner, width, true);
    ninePatchIcon.addVerticalStretch(0, inner, true);
    ninePatchIcon.addVerticalStretch(inner + 1, width - inner - 1, false);
    ninePatchIcon.addVerticalStretch(width - inner, width, true);
    ninePatchIcon.setMargin(shadeWidth);
    return ninePatchIcon;
  }
Example #13
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;
  }
 @Override
 public RenderedImage scaleImage(Image image, int width, int height) {
   // Draw the given image to a buffered image object and scale it to the new size on-the-fly.
   int imageType = BufferedImage.TYPE_4BYTE_ABGR;
   if (image instanceof BufferedImage) {
     imageType = ((BufferedImage) image).getType();
     if (imageType == BufferedImage.TYPE_BYTE_INDEXED
         || imageType == BufferedImage.TYPE_BYTE_BINARY
         || imageType == BufferedImage.TYPE_CUSTOM) {
       // INDEXED and BINARY: GIFs or indexed PNGs may lose their transparent bits, for safety
       // revert to ABGR.
       // CUSTOM: Unknown image type, fall back on ABGR.
       imageType = BufferedImage.TYPE_4BYTE_ABGR;
     }
   }
   BufferedImage bufferedImage = new BufferedImage(width, height, imageType);
   Graphics2D graphics2D = bufferedImage.createGraphics();
   graphics2D.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
   // We should test the return code here because an exception can be throw but caught.
   if (!graphics2D.drawImage(image, 0, 0, width, height, null)) {
     // Conversion failed.
     throw new RuntimeException("Failed to resize image.");
   }
   return bufferedImage;
 }
Example #15
0
  /**
   * 将照片logo添加到二维码中间
   *
   * @param image 生成的二维码照片对象
   * @param imagePath 照片保存路径
   * @param logoPath logo照片路径
   * @param formate 照片格式
   */
  public static void overlapImage(
      BufferedImage image,
      String formate,
      String imagePath,
      String logoPath,
      MatrixToLogoImageConfig logoConfig) {
    try {
      BufferedImage logo = ImageIO.read(new File(logoPath));
      Graphics2D g = image.createGraphics();
      // 考虑到logo照片贴到二维码中,建议大小不要超过二维码的1/5;
      int width = image.getWidth() / logoConfig.getLogoPart();
      int height = image.getHeight() / logoConfig.getLogoPart();
      // logo起始位置,此目的是为logo居中显示
      int x = (image.getWidth() - width) / 2;
      int y = (image.getHeight() - height) / 2;
      // 绘制图
      g.drawImage(logo, x, y, width, height, null);

      // 给logo画边框
      // 构造一个具有指定线条宽度以及 cap 和 join 风格的默认值的实心 BasicStroke
      g.setStroke(new BasicStroke(logoConfig.getBorder()));
      g.setColor(logoConfig.getBorderColor());
      g.drawRect(x, y, width, height);

      g.dispose();
      // 写入logo照片到二维码
      ImageIO.write(image, formate, new File(imagePath));
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  @Test
  public void testTranslatedImage() {
    BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY);
    Graphics g = image.createGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(236, 236, 20, 20);
    g.setColor(new Color(80, 80, 80)); // A dark gray
    g.fillRect(216, 216, 20, 20);
    g.setColor(new Color(200, 200, 200)); // A light gray
    g.fillRect(216, 236, 20, 20);
    g.dispose();
    image = image.getSubimage(128, 128, 128, 128);
    CustomPaletteBuilder builder = new CustomPaletteBuilder(image, 256, 1, 1, 1);
    RenderedImage indexed = builder.buildPalette().getIndexedImage();
    assertTrue(indexed.getColorModel() instanceof IndexColorModel);
    IndexColorModel icm = (IndexColorModel) indexed.getColorModel();
    assertEquals(
        4,
        icm
            .getMapSize()); // Black background, white fill, light gray fill, dark gray fill = 4
                            // colors

    // check image not black
    ImageWorker iw = new ImageWorker(indexed).forceComponentColorModel().intensity();
    double[] mins = iw.getMinimums();
    double[] maxs = iw.getMaximums();
    boolean result = true;
    for (int i = 0; i < mins.length; i++) {
      result = mins[i] == maxs[i] ? false : result;
    }
    assertTrue(result);
  }
  private BufferedImage scale(BufferedImage image, int newWidth, int newHeight) {
    float width;
    float height;

    if (newWidth <= 0 || newHeight <= 0) {
      logger.warn("Invalid scale attempt aborted.");
      return null;
    }

    width = (float) newWidth / (float) image.getWidth();
    height = (float) newHeight / (float) image.getHeight();

    BufferedImage out = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = out.createGraphics();
    RenderingHints qualityHints =
        new RenderingHints(
            RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ANTIALIAS_ON);
    qualityHints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHints(qualityHints);
    AffineTransform at = AffineTransform.getScaleInstance(width, height);
    g2.drawImage(image, at, null);
    g2.dispose();

    return out;
  }
  /* applet init event. Should initialize the applet. */
  public void init() {
    backbuffer = new BufferedImage(512, 512, BufferedImage.TYPE_INT_ARGB);
    g2d = backbuffer.createGraphics();

    iconSheet = getImage(this.getClass().getResource("data/icons2.png"));

    wateringCanImage = getImageFromIconSheet(0, 0);
    wateringSplashImage = getImageFromIconSheet(1, 0);
    flowerImage = getImageFromIconSheet(2, 0);
    seedImage = getImageFromIconSheet(3, 0);
    skullImage = getImageFromIconSheet(4, 0);
    tapImage = getImageFromIconSheet(5, 0);
    playerImage = getImageFromIconSheet(0, 1);
    flowerStalkImage = getImageFromIconSheet(2, 1);
    clockImage = getImageFromIconSheet(4, 1);
    tapSplashImage = getImageFromIconSheet(5, 1);
    dirtImage = getImageFromIconSheet(0, 2);
    brickImage = getImageFromIconSheet(0, 3);

    player.image = playerImage;

    pickupAudio = getAudioClip(this.getClass().getResource("data/Pickup.wav"));

    for (int i = 0; i < 14; i++) {
      flowerList[i] = new Flower();
      flowerList[i].height = rand.nextInt(14);
    }

    addKeyListener(this);
  }
Example #19
0
 /**
  * 插入LOGO
  *
  * @param source 二维码图片
  * @param imgPath LOGO图片地址
  * @param needCompress 是否压缩
  * @throws Exception
  */
 private static void insertImage(BufferedImage source, String imgPath, boolean needCompress)
     throws Exception {
   File file = new File(imgPath);
   if (!file.exists()) {
     System.err.println("" + imgPath + " 该文件不存在!");
     return;
   }
   Image src = ImageIO.read(new File(imgPath));
   int width = src.getWidth(null);
   int height = src.getHeight(null);
   if (needCompress) { // 压缩LOGO
     if (width > WIDTH) {
       width = WIDTH;
     }
     if (height > HEIGHT) {
       height = HEIGHT;
     }
     Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
     BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
     Graphics g = tag.getGraphics();
     g.drawImage(image, 0, 0, null); // 绘制缩小后的图
     g.dispose();
     src = image;
   }
   // 插入LOGO
   Graphics2D graph = source.createGraphics();
   int x = (QRCODE_WIDTH - width) / 2;
   int y = (QRCODE_HEIGHT - height) / 2;
   graph.drawImage(src, x, y, width, height, null);
   Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
   graph.setStroke(new BasicStroke(3f));
   graph.draw(shape);
   graph.dispose();
 }
Example #20
0
 public void run() {
   BufferedImage img = panel.getImage();
   Graphics2D g2 = img.createGraphics();
   int anzahl = 255;
   int st = 6;
   int r = st / 2;
   int x1, y1;
   int c;
   Random random = new Random();
   MyColor myColor = MyColor.getInstance();
   for (int y = 0; y < img.getHeight(); y += st) {
     for (Integer x = 0; x < img.getWidth(); x += st) {
       int color = img.getRGB(x, y);
       if (color != RED && color != WHITE) {
         c = 0;
         for (int i = 0; i < anzahl; i++) {
           x1 = x;
           y1 = y;
           color = BLACK;
           while (color != RED && color != WHITE) {
             x1 += random.nextBoolean() ? 5 : -5;
             y1 += random.nextBoolean() ? 5 : -5;
             color = img.getRGB(x1, y1);
           }
           if (color == RED) {
             c += 1;
           }
         }
         System.out.println("Point(" + x + "," + y + ")  c=" + c);
         g2.setColor(myColor.getColorAt(c));
         g2.fillOval(x - r, y - r, st, st);
       }
     }
   }
 }
Example #21
0
  void registerImage(URL imageURL) {
    if (loadedImages.containsKey(imageURL)) {
      return;
    }

    SoftReference ref;
    try {
      String fileName = imageURL.getFile();
      if (".svg".equals(fileName.substring(fileName.length() - 4).toLowerCase())) {
        SVGIcon icon = new SVGIcon();
        icon.setSvgURI(imageURL.toURI());

        BufferedImage img =
            new BufferedImage(
                icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        icon.paintIcon(null, g, 0, 0);
        g.dispose();
        ref = new SoftReference(img);
      } else {
        BufferedImage img = ImageIO.read(imageURL);
        ref = new SoftReference(img);
      }
      loadedImages.put(imageURL, ref);
    } catch (Exception e) {
      Logger.getLogger(SVGConst.SVG_LOGGER)
          .log(Level.WARNING, "Could not load image: " + imageURL, e);
    }
  }
  /**
   * returns the resized and cliped img.
   *
   * @param img
   * @param newW
   * @param newH
   * @return
   */
  private static BufferedImage resizeclip(BufferedImage img, int newW, int newH) {

    int startx, width, starty, height;
    int w = img.getWidth();
    int h = img.getHeight();
    double sourceVer = 1.0 * h / w;
    double targetVer = 1.0 * newH / newW;
    if (sourceVer < targetVer) {
      starty = 0;
      height = h;
      startx = (int) (((1.0 * newH / h * w - newW) / 2) * 1.0 * h / newH);
      width = startx + (int) (newW * 1.0 * h / newH);
    } else {
      startx = 0;
      width = w;
      starty = (int) (((1.0 * newW / w * h - newH) / 2) * 1.0 * w / newW);
      height = starty + (int) (newH * 1.0 * w / newW);
    }
    BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
    Graphics2D g = dimg.createGraphics();
    g.setRenderingHint(
        RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(img, 0, 0, newW, newH, startx, starty, width, height, null);
    g.dispose();
    return dimg;
  }
  public void run(String[] args) {
    File inDir = new File("input/SampleZoomLevel");
    File outFile = new File("output/SampleZoomLevel/map.png");
    File[] fileList = inDir.listFiles();

    int i;
    // Stitching a map with 4 rows and 4 columns; the program is generalized,
    // so you can use higher multiples of 4, such as 8 by 8 and 16 by 16.
    int rows = 4;
    int cols = 4;
    int total = rows * cols;

    BufferedImage images[] = new BufferedImage[total];

    try {
      for (i = 0; i < total; i++) {
        File inFile = fileList[i];

        int c1;
        int c2;
        // The code below deals with the naming convention we use
        // for each map tile.
        // See the ReadMe for more on the naming convention.
        String s = inFile.getName().substring(0, 2);
        c1 = Integer.parseInt(s);
        s = inFile.getName().substring(3, 5);
        c2 = Integer.parseInt(s);

        BufferedImage image = null;

        image = ImageIO.read(inFile);
        images[c1 * cols + c2] = image;
      }

    } catch (IOException e) {
      System.err.println(e);
      System.exit(1);
    }

    // Our map tiles are square, with dimensions of 256 by 256 pixels.  With 4 rows and 	//4
    // columns, we create a 1024 by 1024 image.

    BufferedImage outputImage =
        new BufferedImage(256 * cols, 256 * rows, BufferedImage.TYPE_INT_ARGB_PRE);
    Graphics2D g = outputImage.createGraphics();

    // Loop through the rows and columns
    for (i = 0; i < rows; i++) {
      for (int j = 0; j < cols; j++) {
        g.drawImage(images[i * cols + j], j * 256, i * 256, 256, 256, null);
      }
    }

    try {
      ImageIO.write(outputImage, "png", outFile);
    } catch (IOException e) {
      System.err.println(e);
      System.exit(1);
    }
  }
Example #24
0
 public void update(long elapsedTime) {
   if (visible && timer.action(elapsedTime)) {
     this.tmp_img = GraphicsUtils.createImage(width, height, true);
     this.graphics2D = tmp_img.createGraphics();
     for (int i = 0; i < max; i++) {
       if (maxs[i] == flag || maxs[i] == -flag) {
         bools[i] = !bools[i];
       }
       maxs[i] += bools[i] ? 1 : -1;
       if (d[i] == 0
           && (matching == i
               || matching < 0
                   && abs(randx - xs[i] - sakura_width / 2) < sakura_width / 2
                   && abs(randy - ys[i] - sakura_height / 2) < sakura_height / 2)) {
         xs[i] = randx - sakura_width / 2;
         ys[i] = randy - sakura_height / 2;
         maxs[i] = 0;
         matching = i;
       } else {
         xs[i] += maxs[i];
         if (ys[i] < height) {
           ys[i] += s[i];
         } else {
           xs[i] = (int) (LSystem.random.nextFloat() * (width - 1));
           ys[i] = -(int) (LSystem.random.nextFloat() * 1) - images[d[i]].getHeight(null);
         }
       }
       this.tmp_x = xs[i];
       this.tmp_y = ys[i];
       graphics2D.drawImage(images[d[i]], tmp_x, tmp_y, null);
     }
   }
 }
Example #25
0
  private BufferedImage resizeImg(InputStream inputStream) throws IOException {
    BufferedImage originalImage = ImageIO.read(inputStream);
    int width = originalImage.getWidth();
    int height = originalImage.getHeight();

    int newWidth = width;
    int newHeight = height;
    // Ajusta o height de acordo com o min width
    if (width > MAX_WIDTH) {
      newWidth = MAX_WIDTH;
      newHeight = (newWidth * height) / width;

      width = newWidth;
      height = newHeight;
    }
    // Ajusta o width de acordo com o min height
    if (height > MAX_HEIGHT) {
      newHeight = MAX_HEIGHT;
      newWidth = (newHeight * width) / height;

      width = newWidth;
      height = newHeight;
    }

    BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, width, height, null);
    g.dispose();

    return resizedImage;
  }
  /**
   * Draws contours. Internal and external contours are different user specified colors.
   *
   * @param contours List of contours
   * @param colorExternal RGB color
   * @param colorInternal RGB color
   * @param width Image width
   * @param height Image height
   * @param out (Optional) storage for output image
   * @return Rendered contours
   */
  public static BufferedImage renderContours(
      List<Contour> contours,
      int colorExternal,
      int colorInternal,
      int width,
      int height,
      BufferedImage out) {

    if (out == null) {
      out = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    } else {
      Graphics2D g2 = out.createGraphics();
      g2.setColor(Color.BLACK);
      g2.fillRect(0, 0, width, height);
    }

    for (Contour c : contours) {
      for (Point2D_I32 p : c.external) {
        out.setRGB(p.x, p.y, colorExternal);
      }
      for (List<Point2D_I32> l : c.internal) {
        for (Point2D_I32 p : l) {
          out.setRGB(p.x, p.y, colorInternal);
        }
      }
    }

    return out;
  }
 /**
  * returns the resized img with black bars.
  *
  * @param img
  * @param newW
  * @param newH
  * @return
  */
 private static BufferedImage resize(BufferedImage img, int newW, int newH) {
   int startx, wide, starty, hight;
   int w = img.getWidth();
   int h = img.getHeight();
   double sourceVer = 1.0 * h / w;
   double targetVer = 1.0 * newH / newW;
   if (sourceVer < targetVer) {
     startx = 0;
     wide = newW;
     hight = (int) 1.0 * newW / w * h;
     starty = (int) (newH - hight) / 2;
     hight += starty;
   } else {
     starty = 0;
     hight = newH;
     wide = (int) 1.0 * newH / h * w;
     startx = (int) (newW - wide) / 2;
     wide += startx;
   }
   BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());
   Graphics2D g = dimg.createGraphics();
   g.setRenderingHint(
       RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
   Color color = new Color(0, 0, 0);
   g.setColor(color);
   g.fillRect(0, 0, startx == 0 ? newW : startx, starty == 0 ? newH : starty);
   g.drawImage(img, startx, starty, wide, hight, 0, 0, w, h, null);
   g.fillRect(
       startx == 0 ? 0 : wide,
       starty == 0 ? 0 : hight,
       startx == 0 ? newW : startx,
       starty == 0 ? newH : starty);
   g.dispose();
   return dimg;
 }
Example #28
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;
  }
  @Override
  public void setup() {
    super.setup();
    int sWidth = overrideData.getWidth();
    int sHeight = overrideData.getHeight();

    pixels = new int[tileSizeSquare];
    if (tileSizeBase == sWidth && tileSizeBase == sHeight) {
      overrideData.getRGB(0, 0, sWidth, sHeight, pixels, 0, sWidth);
    } else {
      BufferedImage tmp = new BufferedImage(tileSizeBase, tileSizeBase, 6);
      Graphics2D gfx = tmp.createGraphics();
      gfx.drawImage(
          overrideData,
          0,
          0,
          tileSizeBase,
          tileSizeBase,
          0,
          0,
          sWidth,
          sHeight,
          (ImageObserver) null);
      tmp.getRGB(0, 0, tileSizeBase, tileSizeBase, pixels, 0, tileSizeBase);
      gfx.dispose();
    }

    update();
  }
  public static BufferedImage renderContours(
      List<EdgeContour> edges, int colors[], int width, int height, BufferedImage out) {

    if (out == null) {
      out = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    } else {
      Graphics2D g2 = out.createGraphics();
      g2.setColor(Color.BLACK);
      g2.fillRect(0, 0, width, height);
    }

    colors = checkColors(colors, edges.size());

    for (int i = 0; i < edges.size(); i++) {
      EdgeContour e = edges.get(i);
      int color = colors[i];

      for (EdgeSegment s : e.segments) {
        for (Point2D_I32 p : s.points) {
          out.setRGB(p.x, p.y, color);
        }
      }
    }

    return out;
  }