private float getComplexity(BufferedImage img) {
   // Uses its own resizing method to remove color in the same step
   BufferedImage sml = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_BYTE_GRAY);
   sml.getGraphics().drawImage(img, 0, 0, SIZE, SIZE, null);
   float ret = 0;
   int w = sml.getWidth();
   int h = sml.getHeight();
   Kernel laplace = new Kernel(3, 3, new float[] {1, 1, 1, 1, -8, 1, 1, 1, 1});
   ConvolveOp filter = new ConvolveOp(laplace);
   BufferedImage dest = filter.createCompatibleDestImage(sml, null);
   filter.filter(sml, dest);
   WritableRaster data = dest.getRaster();
   int[] pixels = data.getPixels(0, 0, w, h, new int[w * h]);
   int sum = 0;
   for (int i = 0; i < w; i++) {
     for (int j = 0; j < h; j++) {
       int temp = pixels[i + j * w];
       sum += temp;
     }
   }
   ret = (float) sum / (w * h * 256);
   if (ret < 0.01) {
     ret = 1;
   }
   return ret;
 }
Example #2
0
  /**
   * Aplica una operación de convolución sobre la imagen pasada como argumento, utilizando la matriz
   * también pasada como argumento.
   *
   * @param filtro
   * @param imagen
   * @param tratBordes
   * @return imagen resultante de aplicar el filtro, null en caso de fallo o argumentos incorrectos.
   */
  public static BufferedImage aplicar(float filtro[][], BufferedImage imagen, int tratBordes) {
    BufferedImage res = null;

    if (imagen == null) throw new IllegalArgumentException("La imagen no puede ser nula");
    if (filtro == null || filtro.length == 0)
      throw new IllegalArgumentException("Debe pasarse algún filtro válido");

    if (tratBordes != SIN_BORDES || tratBordes != BORDES_0) tratBordes = SIN_BORDES;

    int width = filtro.length;
    int height = filtro[0].length;
    int tam = width * height;
    float filtroK[] = new float[tam];

    // Creamos el filtro
    for (int i = 0; i < width; i++) {
      for (int j = 0; j < height; j++) {
        filtroK[i * width + j] = filtro[i][j];
      }
    }

    // Creamos la operación de convolución.
    Kernel kernel = new Kernel(width, height, filtroK);
    ConvolveOp cop = new ConvolveOp(kernel, tratBordes, null);

    // Creamos la imagen nueva a semejanza de la antigua
    res = new BufferedImage(imagen.getWidth(), imagen.getHeight(), imagen.getType());

    // Aplicamos el filtro
    cop.filter(imagen, res);

    return res;
  }
Example #3
0
 public BufferedImage getBlur() {
   float[] data = {
     0.1111F, 0.1111F, 0.1111F, 0.1111F, 0.1111F, 0.1111F, 0.1111F, 0.1111F, 0.1111F
   };
   ConvolveOp cop = new ConvolveOp(new Kernel(3, 3, data));
   return this.image = cop.filter(this.image, null);
 }
Example #4
0
  private void resizeImage(String fileName) {
    try {
      Image image = javax.imageio.ImageIO.read(new File(file));
      int imageWidth = image.getWidth(null);
      int imageHeight = image.getHeight(null);

      float scale =
          getRatio(
              imageWidth,
              imageHeight,
              Integer.parseInt(textWidth.getText()),
              Integer.parseInt(textWidth.getText()));
      imageWidth = (int) (scale * imageWidth);
      imageHeight = (int) (scale * imageHeight);

      image = image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_AREA_AVERAGING);
      // Make a BufferedImage from the Image.
      mBufferedImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = mBufferedImage.createGraphics();

      // Map readeringHint = new HashMap();
      // readeringHint.put(RenderingHints.KEY_ALPHA_INTERPOLATION,
      // RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
      // readeringHint.put(RenderingHints.KEY_ANTIALIASING,
      // RenderingHints.VALUE_ANTIALIAS_ON);
      // readeringHint.put(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
      // readeringHint.put(RenderingHints.KEY_DITHERING,
      // RenderingHints.VALUE_DITHER_ENABLE);
      // readeringHint.put(RenderingHints.KEY_INTERPOLATION,
      // RenderingHints.VALUE_INTERPOLATION_BILINEAR);//VALUE_INTERPOLATION_BICUBIC
      // readeringHint.put(RenderingHints.KEY_RENDERING,
      // RenderingHints.VALUE_RENDER_QUALITY);
      // g.setRenderingHints(readeringHint);

      g2.drawImage(image, 0, 0, imageWidth, imageHeight, Color.white, null);

      float[] kernelData2 = {
        -0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f
      };
      Kernel kernel = new Kernel(3, 3, kernelData2);
      ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
      mBufferedImage = cOp.filter(mBufferedImage, null);
      repaint();
      // file = ImageCompress.getFilePath(file) +
      // ImageCompress.getFileName(file) + "-s." +
      // ImageCompress.getFileExt(file).toLowerCase();
      // FileOutputStream out = new FileOutputStream(file);
      // JPEGEncodeParam param =
      // encoder.getDefaultJPEGEncodeParam(bufferedImage);
      // param.setQuality(0.9f, true);
      // encoder.setJPEGEncodeParam(param);
      // JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      // encoder.encode(mBufferedImage);
      // out.close();
    } catch (IOException e) {
    }
  }
 public void gaussianBlur() {
   filtered = null;
   // Kernel kernel = new Kernel(5, 5, makeGaussianKernel(5, 1.4f));
   Kernel kernel = new Kernel(5, 5, gaus);
   ConvolveOp op = new ConvolveOp(kernel);
   filtered = op.filter(greyScale, null);
   ImageIcon icon2 = new ImageIcon(filtered);
   lbl2.setIcon(icon2);
 }
Example #6
0
  public static void ImageScale(String sourceImg, String targetImg, int width, int height) {
    try {
      Image image = javax.imageio.ImageIO.read(new File(sourceImg));
      int imageWidth = image.getWidth(null);
      int imageHeight = image.getHeight(null);
      float scale = getRatio(imageWidth, imageHeight, width, height);
      imageWidth = (int) (scale * imageWidth);
      imageHeight = (int) (scale * imageHeight);

      image = image.getScaledInstance(imageWidth, imageHeight, Image.SCALE_AREA_AVERAGING);
      // Make a BufferedImage from the Image.
      BufferedImage mBufferedImage =
          new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = mBufferedImage.createGraphics();

      // Map readeringHint = new HashMap();
      // readeringHint.put(RenderingHints.KEY_ALPHA_INTERPOLATION,
      // RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
      // readeringHint.put(RenderingHints.KEY_ANTIALIASING,
      // RenderingHints.VALUE_ANTIALIAS_ON);
      // readeringHint.put(RenderingHints.KEY_COLOR_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
      // readeringHint.put(RenderingHints.KEY_DITHERING,
      // RenderingHints.VALUE_DITHER_ENABLE);
      // readeringHint.put(RenderingHints.KEY_INTERPOLATION,
      // RenderingHints.VALUE_INTERPOLATION_BILINEAR);//VALUE_INTERPOLATION_BICUBIC
      // readeringHint.put(RenderingHints.KEY_RENDERING,
      // RenderingHints.VALUE_RENDER_QUALITY);
      // g.setRenderingHints(readeringHint);

      g2.drawImage(image, 0, 0, imageWidth, imageHeight, Color.white, null);
      g2.dispose();

      float[] kernelData2 = {
        -0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f
      };
      Kernel kernel = new Kernel(3, 3, kernelData2);
      ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
      mBufferedImage = cOp.filter(mBufferedImage, null);
      FileOutputStream out = new FileOutputStream(targetImg);
      // JPEGEncodeParam param =
      // encoder.getDefaultJPEGEncodeParam(bufferedImage);
      // param.setQuality(0.9f, true);
      // encoder.setJPEGEncodeParam(param);
      JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
      encoder.encode(mBufferedImage);
      out.close();
    } catch (FileNotFoundException fnf) {
    } catch (IOException ioe) {
    } finally {

    }
  }
  public static ImageIcon getBigSystemIcon(Image image) throws Exception {
    if ((image.getWidth(null) < 20) || (image.getHeight(null) < 20)) {
      if (image.getWidth(null) > image.getHeight(null)) {
        width = 24;
        height = (image.getHeight(null) * 24) / image.getWidth(null);
      } else {
        height = 24;
        width = (image.getWidth(null) * 24) / image.getHeight(null);
      }
    } else {
      return new ImageIcon(image);
    }

    dest = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    dest2 = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

    g = dest.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, 22, 22);
    g.drawImage(image, 0, 0, width, height, null);

    g.dispose();

    sharpenOperator.filter(dest, dest2);

    return new ImageIcon(dest);
  }
  // MenuItem Event Sharpen
  private void jMenuItem12ActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItem12ActionPerformed

    if (gambarEdit == null) {
      return;
    }
    float[] elements = {0.0f, -1.0f, 0.0f, -1.0f, 5.f, -1.0f, 0.0f, -1.0f, 0.0f};
    Kernel kernel = new Kernel(3, 3, elements);
    ConvolveOp op = new ConvolveOp(kernel);
    BufferedImage filteredImage =
        new BufferedImage(gambarEdit.getWidth(), gambarEdit.getHeight(), gambarEdit.getType());
    op.filter(gambarEdit, filteredImage);
    gambarEdit = filteredImage;
    jLabel2.setIcon(null);
    jLabel2.setIcon(new ImageIcon(gambarEdit));
  } // GEN-LAST:event_jMenuItem12ActionPerformed
  public static Image getScaledInstance(File file) throws Exception {
    srcBImage = javax.imageio.ImageIO.read(file);

    if (srcBImage.getWidth() > srcBImage.getHeight()) {
      width = 100;
      height = (srcBImage.getHeight() * 100) / srcBImage.getWidth();
    } else {
      height = 100;
      width = (srcBImage.getWidth() * 100) / srcBImage.getHeight();
    }

    dest = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
    dest2 = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

    g = dest.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0, 0, 100, 100);
    g.drawImage(srcBImage, 0, 0, width, height, null);

    g.dispose();
    srcBImage = null;
    blurOperator.filter(dest, dest2);

    return dest2;
  }
  public static ImageIcon getSmallSystemIcon(Image img) throws Exception {
    if ((img.getWidth(null) > 20) || (img.getHeight(null) > 20)) {
      if (img.getWidth(null) > img.getHeight(null)) {
        width = 18;
        height = (img.getHeight(null) * 18) / img.getWidth(null);
      } else {
        height = 18;
        width = (img.getWidth(null) * 18) / img.getHeight(null);
      }
    } else {
      return new ImageIcon(img);
    }

    dest = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
    dest2 = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

    g = dest.getGraphics();
    g.drawImage(img, 1, 1, width, height, null);

    g.dispose();

    blurOperator.filter(dest, dest2);

    return new ImageIcon(dest2);
  }
Example #11
0
 private static BufferedImage applyKernelFilter(final BufferedImage source, Kernel customFilter)
     throws IOException, NullPointerException {
   if (verifyNotNull(source)) {
     RenderingHints requiredRenderingHintsForQuality =
         new RenderingHints(
             generateRenderingHintsBasedOnProperties(ImageProcessing.HIGH_BEST_SLOW));
     ConvolveOp bufferedImageOperations =
         new ConvolveOp(customFilter, ConvolveOp.EDGE_NO_OP, requiredRenderingHintsForQuality);
     BufferedImage target =
         new BufferedImage(source.getWidth(), source.getHeight(), source.getType());
     target = bufferedImageOperations.filter(source, target);
     if (verifyNotNull(target)) {
       return target;
     }
     throw new NullPointerException("Internal: Target was null");
   }
   throw new NullPointerException(E_OBJECT_WAS_NULL);
 }
Example #12
0
 /**
  * ����gifͼƬ
  *
  * @param originalFile ԭͼƬ
  * @param resizedFile ���ź��ͼƬ
  * @param newWidth ���
  * @param quality ���ű��� (�ȱ���)
  * @throws IOException
  */
 private static void resize(File originalFile, File resizedFile, int newWidth, float quality)
     throws IOException {
   if (quality < 0 || quality > 1)
     throw new IllegalArgumentException("Quality has to be between 0 and 1");
   ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
   Image i = ii.getImage();
   Image resizedImage = null;
   int iWidth = i.getWidth(null);
   int iHeight = i.getHeight(null);
   if (iWidth > iHeight)
     resizedImage = i.getScaledInstance(newWidth, newWidth * iHeight / iWidth, Image.SCALE_SMOOTH);
   else
     resizedImage = i.getScaledInstance(newWidth * iWidth / iHeight, newWidth, Image.SCALE_SMOOTH);
   // This code ensures that all the pixels in the image are loaded.
   Image temp = new ImageIcon(resizedImage).getImage();
   // Create the buffered image.
   BufferedImage bufferedImage =
       new BufferedImage(temp.getWidth(null), temp.getHeight(null), BufferedImage.TYPE_INT_RGB);
   // Copy image to buffered image.
   Graphics g = bufferedImage.createGraphics();
   // Clear background and paint the image.
   g.setColor(Color.white);
   g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
   g.drawImage(temp, 0, 0, null);
   g.dispose();
   // Soften.
   float softenFactor = 0.05f;
   float[] softenArray = {
     0, softenFactor, 0, softenFactor, 1 - softenFactor * 4, softenFactor, 0, softenFactor, 0
   };
   Kernel kernel = new Kernel(3, 3, softenArray);
   ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
   bufferedImage = cOp.filter(bufferedImage, null);
   // Write the jpeg to a file.
   FileOutputStream out = new FileOutputStream(resizedFile);
   // Encodes image as a JPEG data stream
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
   param.setQuality(quality, true);
   encoder.setJPEGEncodeParam(param);
   encoder.encode(bufferedImage);
 }
Example #13
0
  public void process(String srcImageFile) {
    try {
      Image img;
      ImageFilter cropFilter;
      // 读取源图像
      BufferedImage bi = ImageIO.read(new File(srcImageFile));
      int srcWidth = bi.getWidth(); // 源图宽度
      int srcHeight = bi.getHeight(); // 源图高度

      int destLength = srcWidth > srcHeight ? srcHeight : srcWidth;
      int x = (srcWidth - destLength) / 2;
      int y = (srcHeight - destLength) / 2;
      logger.debug(
          String.format(
              "ImgUtil -----> picUrl: %s,srcWidth %d,srcHeight:%d",
              srcImageFile, srcWidth, srcHeight));

      cropFilter = new CropImageFilter(x, y, destLength, destLength);
      img =
          Toolkit.getDefaultToolkit()
              .createImage(new FilteredImageSource(bi.getSource(), cropFilter));

      BufferedImage tag = new BufferedImage(destLength, destLength, BufferedImage.TYPE_INT_RGB);
      Graphics g = tag.getGraphics();
      g.drawImage(img, 0, 0, null); // 绘制截取后的图
      g.dispose();

      logger.debug("ImgUtil -----> Cut finished");

      // 压缩
      for (String s : compressSizeList.keySet()) {
        int length = compressSizeList.get(s);
        // To Test
        Image tmpResult = tag.getScaledInstance(length, length, Image.SCALE_DEFAULT);
        BufferedImage mBufferedImage =
            new BufferedImage(length, length, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = mBufferedImage.createGraphics();

        g2.drawImage(tmpResult, 0, 0, length, length, Color.white, null);
        g2.dispose();

        float[] kernelData2 = {
          -0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f
        };
        Kernel kernel = new Kernel(3, 3, kernelData2);
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        mBufferedImage = cOp.filter(mBufferedImage, null);

        String targetImageFile = getPictureSmallURL(srcImageFile, s);

        File target = new File(targetImageFile);
        File targetDir = target.getParentFile();
        if (!targetDir.exists()) targetDir.mkdirs();

        // 输出为文件
        FileOutputStream out = new FileOutputStream(targetImageFile);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        encoder.encode(mBufferedImage);
        out.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #14
0
 public BufferedImage getSharpen() {
   float[] data = {0.0F, -0.75F, 0.0F, -0.75F, 4.0F, -0.75F, 0.0F, -0.75F, 0.0F};
   ConvolveOp cop = new ConvolveOp(new Kernel(3, 3, data));
   return this.image = cop.filter(this.image, null);
 }
Example #15
0
 public static BufferedImage sharpen(BufferedImage bi) {
   float elements[] = {-1.0f, -1.0f, -1.0f, -1.0f, 9.0f, -1.0f, -1.0f, -1.0f, -1.0f};
   ConvolveOp convolve = new ConvolveOp(new Kernel(3, 3, elements));
   return convolve.filter(bi, null);
 }
Example #16
0
 public static BufferedImage edgeDetect(BufferedImage bi) {
   float elements[] = {1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, -1.0f};
   ConvolveOp convolve = new ConvolveOp(new Kernel(3, 3, elements));
   return convolve.filter(bi, null);
 }
Example #17
0
  static void paintShadowTitle(
      Graphics g,
      String title,
      int x,
      int y,
      Color frente,
      Color shadow,
      int desp,
      int tipo,
      int orientation) {

    // Si hay que rotar la fuente, se rota
    Font f = g.getFont();
    if (orientation == SwingConstants.VERTICAL) {
      AffineTransform rotate = AffineTransform.getRotateInstance(Math.PI / 2);
      f = f.deriveFont(rotate);
    }

    // Si hay que pintar sombra, se hacen un monton de cosas
    if (shadow != null) {
      int matrix = (tipo == THIN ? MATRIX_THIN : MATRIX_FAT);

      Rectangle2D rect = g.getFontMetrics().getStringBounds(title, g);

      int w, h;
      if (orientation == SwingConstants.HORIZONTAL) {
        w = (int) rect.getWidth() + 6 * matrix; // Hay que dejar espacio para las sombras y el borde
        h = (int) rect.getHeight() + 6 * matrix; // que ConvolveOp ignora por el EDGE_NO_OP
      } else {
        h = (int) rect.getWidth() + 6 * matrix; // Hay que dejar espacio para las sombras y el borde
        w = (int) rect.getHeight() + 6 * matrix; // que ConvolveOp ignora por el EDGE_NO_OP
      }

      // La sombra del titulo
      BufferedImage iTitulo = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
      BufferedImage iSombra = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

      Graphics2D g2 = iTitulo.createGraphics();
      g2.setRenderingHint(
          RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

      g2.setFont(f);
      g2.setColor(shadow);
      g2.drawString(title, 3 * matrix, 3 * matrix); // La pintamos en el centro

      ConvolveOp cop =
          new ConvolveOp((tipo == THIN ? kernelThin : kernelFat), ConvolveOp.EDGE_NO_OP, null);
      cop.filter(iTitulo, iSombra); // A ditorsionar

      // Por fin, pintamos el jodio titulo
      g.drawImage(
          iSombra,
          x - 3 * matrix + desp, // Lo llevamos a la posicion original y le sumamos 1
          y - 3 * matrix + desp, // para que la sombra quede pelin desplazada
          null);
    }

    // Si hay que pintar el frente, se pinta
    if (frente != null) {
      g.setFont(f);
      g.setColor(frente);
      g.drawString(title, x, y);
    }
  }