@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;
 }
  /**
   * Alter the color of each pixel in the image. Make the image greyscaled.
   *
   * @param bi The BufferedImage on which the color variation is done.
   */
  public static void greyScale(BufferedImage bi) {

    int xSize = bi.getWidth();
    int ySize = bi.getHeight();

    for (int x = 0; x < xSize; x++) {
      for (int y = 0; y < ySize; y++) {
        // return R G B and alpha values in integer form
        int rgb = bi.getRGB(x, y);
        // unpack to get individual integers
        int[] rgbValues = unpackPixel(rgb);
        int alpha = rgbValues[0];
        int red = rgbValues[1];
        int green = rgbValues[2];
        int blue = rgbValues[3];
        int average = (red + green + blue) / 3;
        // get rgb values in integers for manipulation
        if (red <= 255) {
          red = average;
        }
        if (green <= 255) {
          green = average;
        }
        if (blue <= 255) {
          blue = average;
        }

        int newColour = packagePixel(red, green, blue, alpha);
        bi.setRGB(x, y, newColour);
      }
    }
    addImage(bi);
  }
  /**
   * Alter the color of each pixel in the image. Make the image sepia.
   *
   * @param bi The BufferedImage on which the color variation is done.
   */
  public static void sepia(BufferedImage bi) {

    // Get image size
    int xSize = bi.getWidth();
    int ySize = bi.getHeight();
    int sepia = 25;

    for (int x = 0; x < xSize; x++) {
      for (int y = 0; y < ySize; y++) {
        int rgb = bi.getRGB(x, y);

        int[] rgbValues = unpackPixel(rgb);
        int alpha = rgbValues[0];
        int red = rgbValues[1];
        int green = rgbValues[2];
        int blue = rgbValues[3];

        // Equalizes all RGB values, and then uses Sepia depth to increase Red and Green amounts by
        // specified value to achieve sepia effect
        int equalizer = (red + green + blue) / 3;
        red = equalizer + (sepia * 2);
        blue = equalizer;
        green = equalizer + sepia;

        // Restriction for values of RGB so to make sure image does not become over manipulated
        if (red > 255) red = 255;
        if (green > 255) green = 255;
        if (blue > 255) blue = 255;

        int newColour = packagePixel(red, green, blue, alpha);
        bi.setRGB(x, y, newColour);
      }
    }
    addImage(bi);
  }
  public Document createDocument(BufferedImage image, String identifier) {
    assert (image != null);
    BufferedImage bimg = image;
    // Scaling image is especially with the correlogram features very important!
    // All images are scaled to guarantee a certain upper limit for indexing.
    if (Math.max(image.getHeight(), image.getWidth()) > MAX_IMAGE_DIMENSION) {
      bimg = ImageUtils.scaleImage(image, MAX_IMAGE_DIMENSION);
    }
    Document doc = null;
    logger.finer("Starting extraction from image [CEDD - fast].");
    CEDD vd = new CEDD();
    vd.extract(bimg);
    logger.fine("Extraction finished [CEDD - fast].");

    doc = new Document();
    doc.add(new Field(DocumentBuilder.FIELD_NAME_CEDD, vd.getByteArrayRepresentation()));
    if (identifier != null)
      doc.add(
          new Field(
              DocumentBuilder.FIELD_NAME_IDENTIFIER,
              identifier,
              Field.Store.YES,
              Field.Index.NOT_ANALYZED));

    return doc;
  }
Example #5
0
  public static BufferedImage blur(BufferedImage srcImage) {
    int w = srcImage.getWidth();
    int h = srcImage.getHeight();

    int[] src = srcImage.getRGB(0, 0, w, h, null, 0, w);
    int[] dst = new int[src.length];

    System.out.println("Array size is " + src.length);
    System.out.println("Threshold is " + sThreshold);

    int processors = Runtime.getRuntime().availableProcessors();
    System.out.println(
        Integer.toString(processors)
            + " processor"
            + (processors != 1 ? "s are " : " is ")
            + "available");

    ForkBlur fb = new ForkBlur(src, 0, src.length, dst);

    ForkJoinPool pool = new ForkJoinPool();

    long startTime = System.currentTimeMillis();
    pool.invoke(fb);
    long endTime = System.currentTimeMillis();

    System.out.println("Image blur took " + (endTime - startTime) + " milliseconds.");

    BufferedImage dstImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    dstImage.setRGB(0, 0, w, h, dst, 0, w);

    return dstImage;
  }
 // Renders image from canon DSLR
 private static void canonSLR(final CanonCamera camera) {
   renderCanon = new JLabel();
   if (canon = true) {
     while (canon = true) {
       try {
         Thread.sleep(50);
         BufferedImage canonimage = camera.downloadLiveView();
         if (canonimage != null) {
           renderCanon.setIcon(new ImageIcon(canonimage));
           renderCanon.setBounds((width / 2) - 528, 10, 1056, 704);
           renderCanon.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 3));
           renderCanon.setToolTipText("Live Canon DSLR feed");
           renderCanon.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
           window.add(renderCanon);
           webcam = false;
           nikon = false;
           System.out.println("Battery: " + camera.getProperty(kEdsPropID_BatteryLevel));
           canonimage.flush();
         }
       } catch (InterruptedException ex) {
         Logger.getLogger(Controls.class.getName()).log(Level.SEVERE, null, ex);
       }
     }
   }
 }
 /**
  * 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;
 }
    public void paint(java.awt.Graphics g) {

      int w = m_bi.getWidth(this);

      int h = m_bi.getHeight(this);

      // int ww= (int)(w*(percentSize/100));

      // int hh=(int)(h*(percentSize/100));

      g.setColor(java.awt.Color.white);

      g.fillRect(0, 0, this.getWidth(), this.getHeight());

      java.awt.Graphics2D g2d = (java.awt.Graphics2D) g;

      g2d.scale(percentSize / 100.0, percentSize / 100.0);

      int ml = (this.getWidth() / 2) - (w / 2);

      int mh = (this.getHeight() / 2) - (h / 2);

      if (m_bi != null) {
        g2d.drawImage(m_bi, ml, mh, this);
      }
    }
Example #9
0
  private static double[] getHist(ImageData queryImage) throws IOException {
    BufferedImage image = queryImage.getImage();
    int imHeight = image.getHeight();
    int imWidth = image.getWidth();
    double[] bins = new double[dim * dim * dim];
    int step = 256 / dim;
    Raster raster = image.getRaster();
    for (int i = 0; i < imWidth; i++) {
      for (int j = 0; j < imHeight; j++) {
        // rgb->ycrcb
        int r = raster.getSample(i, j, 0);
        int g = raster.getSample(i, j, 1);
        int b = raster.getSample(i, j, 2);

        // Changed Codes.
        int y = (int) (0 + 0.299 * r + 0.587 * g + 0.114 * b);
        int cb = (int) (128 - 0.16874 * r - 0.33126 * g + 0.50000 * b);
        int cr = (int) (128 + 0.50000 * r - 0.41869 * g - 0.08131 * b);

        int ybin = y / step;
        int cbbin = cb / step;
        int crbin = cr / step;

        // Changed Codes.
        bins[ybin * dim * dim + cbbin * dim + crbin]++;
      }
    }

    // Changed Codes.
    for (int i = 0; i < dim * dim * dim; i++) {
      bins[i] = bins[i] / (imHeight * imWidth);
    }
    return bins;
  }
Example #10
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();
    }
  }
Example #11
0
  public static void main(String[] args)
      throws DocumentException, MalformedURLException, IOException {

    BufferedImage image = ImageIO.read(imageFile);

    BufferedImage bi =
        new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
    ColorConvertOp xformOp = new ColorConvertOp(null);
    xformOp.filter(image, bi);

    // bi.setData(icon.getData());

    WritableRaster raster = bi.getRaster();
    DataBufferInt data = (DataBufferInt) raster.getDataBuffer();

    int[] intData = data.getData();

    ByteBuffer byteBuffer = ByteBuffer.allocate(intData.length * 4);
    IntBuffer intBuffer = byteBuffer.asIntBuffer();
    intBuffer.put(intData);

    byte[] array = byteBuffer.array();

    System.out.println(Hex.encodeHex(array));
  }
  /**
   * Helper function to convert a Mat into a BufferedImage. Taken from
   * http://answers.opencv.org/question/10344/opencv-java-load-image-to-gui Author: 'Lucky Luke'
   *
   * @param matrix Mat of type CV_8UC3 or CV_8UC1
   * @return BufferedImage of type TYPE_3BYTE_BGR or TYPE_BYTE_GRAY
   */
  private static BufferedImage matToBufferedImage(Mat matrix) {
    int cols = matrix.cols();
    int rows = matrix.rows();
    int elemSize = (int) matrix.elemSize();
    byte[] data = new byte[cols * rows * elemSize];
    int type;

    matrix.get(0, 0, data);

    switch (matrix.channels()) {
      case 1:
        type = BufferedImage.TYPE_BYTE_GRAY;
        break;

      case 3:
        type = BufferedImage.TYPE_3BYTE_BGR;

        // bgr to rgb
        byte b;
        for (int i = 0; i < data.length; i = i + 3) {
          b = data[i];
          data[i] = data[i + 2];
          data[i + 2] = b;
        }
        break;

      default:
        return null;
    }

    BufferedImage image = new BufferedImage(cols, rows, type);
    image.getRaster().setDataElements(0, 0, cols, rows, data);

    return image;
  }
Example #13
0
  private BufferedImage getFontImage(char ch) {
    // Create a temporary image to extract the character's size
    BufferedImage tempfontImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = (Graphics2D) tempfontImage.getGraphics();
    if (antiAlias == true) {
      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }
    g.setFont(font);
    fontMetrics = g.getFontMetrics();
    int charwidth = fontMetrics.charWidth(ch) + 8;

    if (charwidth <= 0) {
      charwidth = 7;
    }
    int charheight = fontMetrics.getHeight() + 3;
    if (charheight <= 0) {
      charheight = fontSize;
    }

    // Create another image holding the character we are creating
    BufferedImage fontImage;
    fontImage = new BufferedImage(charwidth, charheight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gt = (Graphics2D) fontImage.getGraphics();
    if (antiAlias == true) {
      gt.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    }
    gt.setFont(font);

    gt.setColor(Color.WHITE);
    int charx = 3;
    int chary = 1;
    gt.drawString(String.valueOf(ch), (charx), (chary) + fontMetrics.getAscent());

    return fontImage;
  }
  /**
   * The <code>extractFeature(MediaContent)</code> class loads the media content, convert it to HMMD
   * color space and executes the CSD extraction and quantization.
   *
   * @param image the image to be analyzed.
   * @throws Exception in some cases ...
   */
  public void extractFeature(BufferedImage image) throws Exception {

    // load image to BufferedImage

    double height = image.getHeight();
    double width = image.getWidth();

    int temp[][] = new int[(int) height - 1][(int) width - 1];

    //        if (width > height) {
    //            System.out.println("\nExit - vizir bug: file unsupported ->
    // MediaFrame.getPixelAt");
    //            System.exit(0);
    //        }

    int ir[][] = temp;
    int ig[][] = temp;
    int ib[][] = temp;

    int iH[][] = temp;
    int iMax[][] = temp;
    int iMin[][] = temp;
    int iDiff[][] = temp;
    int iSum[][] = temp;

    // convert BufferedImage to double int array for every RGB color
    // ant then covert RGB values into HMMD

    WritableRaster raster = image.getRaster();
    int[] pixel = new int[3];
    for (int ch = 0; ch < height - 1; ch++) { // row
      for (int cw = 0; cw < width - 1; cw++) { // column
        raster.getPixel(cw, ch, pixel);
        ir[ch][cw] = pixel[0]; // RED
        ig[ch][cw] = pixel[1]; // GREEN
        ib[ch][cw] = pixel[2]; // BLUE

        int[] tempHMMD = RGB2HMMD(ir[ch][cw], ig[ch][cw], ib[ch][cw]);
        iH[ch][cw] = tempHMMD[0]; // H
        iMax[ch][cw] = tempHMMD[1]; // Max
        iMin[ch][cw] = tempHMMD[2]; // Min
        iDiff[ch][cw] = tempHMMD[3]; // Diff
        iSum[ch][cw] = tempHMMD[4]; // Sum
      }
    }

    ColorHistogram =
        HMMDColorStuctureExtraction(
            iH,
            iMax,
            iMin,
            iDiff,
            iSum,
            (int) height,
            (int) width); // extract HMMD colors and make histogram

    // if ( quantizationLevels != 256 ) ColorHistogram = reQuantization(ColorHistogram); //
    // requantize and normalize histogram to 0-255 range
    ColorHistogram = reQuantization(ColorHistogram);
  }
Example #15
0
  /** @param args */
  public static void main(String[] args) {
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File file = chooser.getSelectedFile();
    String indir = file.getAbsolutePath();
    BufferedImage out = null;
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
      out = new BufferedImage(256, 1, BufferedImage.TYPE_INT_RGB);
      String sCurrentLine;
      int pos = 0;
      while ((sCurrentLine = br.readLine()) != null) {
        String[] values = sCurrentLine.split(" ");
        Color ocol =
            new Color(
                Integer.valueOf(values[0]), Integer.valueOf(values[1]), Integer.valueOf(values[2]));
        out.setRGB(pos, 0, ocol.getRGB());
        pos++;
      }
      File outputimage = new File("C:\\ydkj\\palette", "GENPALETTE.bmp");
      ImageIO.write(out, "bmp", outputimage);

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Example #16
0
  public Texture(BufferedImage img) {
    width = img.getWidth();
    height = img.getHeight();
    rgb = new int[width * height];

    img.getRGB(0, 0, width, height, rgb, 0, width);
  }
Example #17
0
  public Bitmap(final BufferedImage image) {
    if (image == null) {
      width = 0;
      height = 0;
      components = new byte[0];
      return;
    }

    int width = 0;
    int height = 0;
    byte[] components = null;
    width = image.getWidth();
    height = image.getHeight();

    final int pixels = width * height;
    components = new byte[pixels * 4];

    int[] imgPixels = new int[pixels];
    image.getRGB(0, 0, width, height, imgPixels, 0, width);

    for (int i = 0; i < pixels; i++) {
      int p = imgPixels[i];
      components[i * 4 + 0] = (byte) ((p >> 24) & 0xFF);
      components[i * 4 + 1] = (byte) ((p) & 0xFF);
      components[i * 4 + 2] = (byte) ((p >> 8) & 0xFF);
      components[i * 4 + 3] = (byte) ((p >> 16) & 0xFF);
    }

    this.width = width;
    this.height = height;
    this.components = components;
  }
  public static BufferedImage doFilter(BufferedImage img) {
    BufferedImage img2 =
        new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
    // img.getSubimage(0, 0, img.getWidth(), img.getHeight());
    for (int i = 0; i < img2.getWidth(); i++) {
      for (int j = 0; j < img2.getHeight(); j++) {
        img2.setRGB(i, j, img.getRGB(i, j));
        // img2.setRGB(i, j, Color.BLACK.getRGB());
      }
    }
    int a = 32;
    for (int j = 0; j < img2.getHeight(); j++) {
      for (int i = 0; i < img2.getWidth(); i++) {
        int c = img.getRGB(i, j);
        Color c2 = new Color(c);
        Error er = new Error();

        er.r = (int) (a * matrix[i % 2][j % 2]);
        er.g = er.r;
        er.b = er.r;
        c2 = addToPixel(c2, er, 1);
        Color c3 = getClosestPixel(c2);
        setPixel(img2, i, j, c3);

        // oldpixel := pixel[x][y] + threshold_map_4x4[x mod 4][y mod 4]
        // newpixel := find_closest_palette_color(oldpixel)
        // pixel[x][y] := newpixel
      }
    }
    return img2;
  }
  /**
   * 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 Image getScreenshot() {
   BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
   Graphics g = image.getGraphics();
   paint(g);
   g.dispose();
   return image;
 }
Example #21
0
 /**
  * Draws only the vertices of the given shape in white. Normals and indices are ignored. TODO:
  * negative W are possible, fix plx?
  *
  * @param shape
  * @param t
  */
 private void drawDotty(Shape shape, Matrix4f t) {
   float[] points = null, colors = null;
   for (VertexElement ve : shape.getVertexData().getElements()) {
     switch (ve.getSemantic()) {
       case POSITION:
         points = ve.getData();
         break;
       case COLOR:
         colors = ve.getData();
         break;
       case NORMAL:
         // DO NOT WANT
         break;
       case TEXCOORD:
         // DO NOT WANT
         break;
     }
   }
   for (int i = 0; i < points.length; i += 3) {
     Point4f v = new Point4f(points[i], points[i + 1], points[i + 2], 1);
     Color3f c = new Color3f(colors[i], colors[i + 1], colors[i + 2]);
     t.transform(v);
     int x = Math.round(v.x / v.w);
     int y = Math.round(v.y / v.w);
     if (x >= 0 && y >= 0 && y < colorBuffer.getHeight() && x < colorBuffer.getWidth())
       drawPointAt(x, y, c.get().getRGB());
   }
 }
Example #22
0
 private Renderer(BufferedImage bi, int[] pixels) {
   super(new DoubleTriangleRasterizer(pixels), false, false);
   // pixels = new int[bi.getWidth()* bi.getHeight()];
   this.pixels = pixels;
   img = bi;
   d = new Dimension(bi.getWidth(), bi.getHeight());
 }
Example #23
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);
    }
  }
Example #24
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!");
 }
  /**
   * Mirrors the image horizontally by reassigning specific pixels around the image.
   *
   * @param bi The BufferedImage on which the translation is done
   */
  public static void mirrorHorizontally(BufferedImage bi) {
    // Get image size to be used in loops to assign rgba values
    int xSize = bi.getWidth();
    int ySize = bi.getHeight();

    // Temp image
    BufferedImage newBi = new BufferedImage(xSize, ySize, 3);
    // mirroring by flipping half an image
    for (int x = 0; x < xSize; x++) {
      for (int y = 0; y < ySize; y++) {
        int rgb = bi.getRGB(xSize - x - 1, y);

        // retrieving the four rgba values using unpack pixel
        int[] rgbValues = unpackPixel(rgb);
        int alpha = rgbValues[0];
        int red = rgbValues[1];
        int green = rgbValues[2];
        int blue = rgbValues[3];
        int newColour =
            packagePixel(
                red, green, blue,
                alpha); // packs pixels to be placed into the buffered image that was initially
                        // used.
        bi.setRGB(x, y, newColour);
      }
    }
    addImage(bi);
  }
Example #26
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;
  }
  /**
   * Alter the color of each pixel in the image. Make the image negatively colored.
   *
   * @param bi The BufferedImage on which the color variation is done.
   */
  public static void negative(BufferedImage bi) {

    int xSize = bi.getWidth();
    int ySize = bi.getHeight();

    for (int x = 0; x < xSize; x++) {
      for (int y = 0; y < ySize; y++) {
        int rgb = bi.getRGB(x, y);

        // calling unpack pixel to get individual values for RGB
        // this allows for manipulation of these values easily
        int[] rgbValues = unpackPixel(rgb);
        int alpha = rgbValues[0];
        int red = rgbValues[1];
        int green = rgbValues[2];
        int blue = rgbValues[3];

        red = 255 - red;
        green = 255 - green;
        blue = 255 - blue;

        int newColour = packagePixel(red, green, blue, alpha);
        bi.setRGB(x, y, newColour);
      }
    }
    addImage(bi);
  }
Example #28
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;
  }
  /**
   * Alter the color of each pixel in the image. Make the image cooler in color.
   *
   * @param bi The BufferedImage on which the color variation is done.
   */
  public static void cooler(BufferedImage bi) {
    int xSize = bi.getWidth();
    int ySize = bi.getHeight();

    for (int x = 0; x < xSize; x++) {
      for (int y = 0; y < ySize; y++) {
        int rgb = bi.getRGB(x, y);

        int[] rgbValues = unpackPixel(rgb);
        int alpha = rgbValues[0];
        int red = rgbValues[1];
        int green = rgbValues[2];
        int blue = rgbValues[3];

        // Apply changes to the rgb value.
        if (blue <= 190) {
          blue += 5;
        }
        if (red >= 130) {
          red--;
        }
        if (green >= 130) {
          green--;
        }

        int newColour = packagePixel(red, green, blue, alpha);
        bi.setRGB(x, y, newColour);
      }
    }
    addImage(bi);
  }
Example #30
0
  public BufferedImage renderFullImage() {
    int scrollX = (int) (getScrollPosition(Orientation.HORIZONTAL) / scale);
    int scrollY = (int) (getScrollPosition(Orientation.VERTICAL) / scale);

    int minChunkX = heightMap.getMinX() + scrollX / 16,
        minChunkZ = heightMap.getMinZ() + scrollY / 16,
        maxChunkX = 0,
        maxChunkZ = 0;
    int horiz = (int) (getWidth() / 16 / scale) + 1;
    int vert = (int) (getHeight() / 16 / scale) + 1;
    maxChunkX = minChunkX + horiz;
    maxChunkZ = minChunkZ + vert;

    minChunkX++;
    minChunkZ++;
    BufferedImage fullImage =
        new BufferedImage(
            (maxChunkX - minChunkX) * 16 + 32,
            (maxChunkZ - minChunkZ) * 16 + 32,
            BufferedImage.TYPE_INT_ARGB);
    for (int chunkX = minChunkX; chunkX <= maxChunkX; chunkX++) {
      for (int chunkZ = minChunkZ; chunkZ <= maxChunkZ; chunkZ++) {
        Map map = drawChunk(chunkX, chunkZ, dirty);
        if (map != null && map != blankMap) {
          Raster raster = map.getColorRaster();
          int startX = (chunkX - minChunkX) * 16;
          int startZ = (chunkZ - minChunkZ) * 16;
          java.awt.image.DataBufferInt buf = (java.awt.image.DataBufferInt) raster.getDataBuffer();
          int[] srcbuf = buf.getData();
          fullImage.setRGB(startX, startZ, 16, 16, srcbuf, 0, 16);
        }
      }
    }
    return fullImage;
  }