public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    int width = src.getWidth();
    int height = src.getHeight();
    int type = src.getType();
    WritableRaster srcRaster = src.getRaster();

    originalSpace = new Rectangle(0, 0, width, height);
    transformedSpace = new Rectangle(0, 0, width, height);
    transformSpace(transformedSpace);

    if (dst == null) {
      ColorModel dstCM = src.getColorModel();
      dst =
          new BufferedImage(
              dstCM,
              dstCM.createCompatibleWritableRaster(transformedSpace.width, transformedSpace.height),
              dstCM.isAlphaPremultiplied(),
              null);
    }
    WritableRaster dstRaster = dst.getRaster();

    int[] inPixels = getRGB(src, 0, 0, width, height, null);
    inPixels = filterPixels(width, height, inPixels, transformedSpace);
    setRGB(dst, 0, 0, transformedSpace.width, transformedSpace.height, inPixels);

    return dst;
  }
 public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel dstCM) {
   if (dstCM == null) dstCM = src.getColorModel();
   return new BufferedImage(
       dstCM,
       dstCM.createCompatibleWritableRaster(src.getWidth(), src.getHeight()),
       dstCM.isAlphaPremultiplied(),
       null);
 }
 public int filterRGB(int x, int y, int rgb) {
   int R, G, B, color;
   ColorModel cm = ColorModel.getRGBdefault();
   if (x == -1) ;
   R = cm.getRed(rgb) & 0xff;
   G = cm.getGreen(rgb) & 0xff;
   B = cm.getBlue(rgb) & 0xff;
   if (R >= 100 && G >= 100 && B >= 100) color = 0xffffffff;
   else color = 0xff000000;
   return color;
 }
  public final BufferedImage filter(BufferedImage src, BufferedImage dst) {
    if (src == dst) {
      // awt.252=Source can't be same as the destination
      throw new IllegalArgumentException(Messages.getString("awt.252")); // $NON-NLS-1$
    }

    ColorModel srcCM = src.getColorModel();
    BufferedImage finalDst = null;

    if (srcCM instanceof IndexColorModel
        && (iType != TYPE_NEAREST_NEIGHBOR || srcCM.getPixelSize() % 8 != 0)) {
      src = ((IndexColorModel) srcCM).convertToIntDiscrete(src.getRaster(), true);
      srcCM = src.getColorModel();
    }

    if (dst == null) {
      dst = createCompatibleDestImage(src, srcCM);
    } else {
      if (!srcCM.equals(dst.getColorModel())) {
        // Treat BufferedImage.TYPE_INT_RGB and
        // BufferedImage.TYPE_INT_ARGB as same
        if (!((src.getType() == BufferedImage.TYPE_INT_RGB
                || src.getType() == BufferedImage.TYPE_INT_ARGB)
            && (dst.getType() == BufferedImage.TYPE_INT_RGB
                || dst.getType() == BufferedImage.TYPE_INT_ARGB))) {
          finalDst = dst;
          dst = createCompatibleDestImage(src, srcCM);
        }
      }
    }

    // Skip alpha channel for TYPE_INT_RGB images
    if (slowFilter(src.getRaster(), dst.getRaster()) != 0) {
      // awt.21F=Unable to transform source
      throw new ImagingOpException(Messages.getString("awt.21F")); // $NON-NLS-1$
      // TODO - uncomment
      // if (ippFilter(src.getRaster(), dst.getRaster(), src.getType()) !=
      // 0)
      // throw new ImagingOpException ("Unable to transform source");
    }

    if (finalDst != null) {
      Graphics2D g = finalDst.createGraphics();
      g.setComposite(AlphaComposite.Src);
      g.drawImage(dst, 0, 0, null);
    } else {
      finalDst = dst;
    }

    return finalDst;
  }
  /**
   * Makes the Mandelbrot image.
   *
   * @param width the width
   * @parah height the height
   * @return the image
   */
  public BufferedImage makeMandelbrot(int width, int height) {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    WritableRaster raster = image.getRaster();
    ColorModel model = image.getColorModel();

    Color fractalColor = Color.red;
    int argb = fractalColor.getRGB();
    Object colorData = model.getDataElements(argb, null);

    for (int i = 0; i < width; i++)
      for (int j = 0; j < height; j++) {
        double a = XMIN + i * (XMAX - XMIN) / width;
        double b = YMIN + j * (YMAX - YMIN) / height;
        if (!escapesToInfinity(a, b)) raster.setDataElements(i, j, colorData);
      }
    return image;
  }
  // This method returns true if the specified image has transparent pixels
  // Source: http://www.exampledepot.com/egs/java.awt.image/HasAlpha.html
  public static boolean hasAlpha(Image image) {
    // If buffered image, the color model is readily available
    if (image instanceof BufferedImage) {
      BufferedImage bimage = (BufferedImage) image;
      return bimage.getColorModel().hasAlpha();
    }

    // Use a pixel grabber to retrieve the image's color model;
    // grabbing a single pixel is usually sufficient
    PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
    try {
      pg.grabPixels();
    } catch (InterruptedException e) {
    }

    // Get the image's color model
    ColorModel cm = pg.getColorModel();
    return cm.hasAlpha();
  }
Exemple #7
0
  public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    int w = src.getWidth();
    int h = src.getHeight();

    if (dst == null) {
      ColorModel dstCM = src.getColorModel();
      dst =
          new BufferedImage(
              dstCM,
              dstCM.createCompatibleWritableRaster(width, height),
              dstCM.isAlphaPremultiplied(),
              null);
    }

    Graphics2D g = dst.createGraphics();
    g.drawRenderedImage(src, AffineTransform.getTranslateInstance(-x, -y));
    g.dispose();

    return dst;
  }
Exemple #8
0
public class Test extends Applet {
  private ColorModel defaultRGB = ColorModel.getRGBdefault();
  private Image image;
  private int imw, imh, pixels[];

  public void init() {
    MediaTracker mt = new MediaTracker(this);

    URL url = getClass().getResource("tiger.gif");

    try {
      image = createImage((ImageProducer) url.getContent());
      mt.addImage(image, 0);
      mt.waitForID(0);
    } catch (Exception e) {
      e.printStackTrace();
    }
    imw = image.getWidth(this);
    imh = image.getWidth(this);
    pixels = new int[imw * imh];

    try {
      PixelGrabber pg = new PixelGrabber(image, 0, 0, imw, imh, pixels, 0, imw);
      pg.grabPixels();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    addMouseMotionListener(
        new MouseMotionAdapter() {
          public void mouseMoved(MouseEvent e) {
            int mx = e.getX(), my = e.getY();

            if (mx > 0 && mx < imw && my > 0 && my < imh) {
              int pixel = ((int[]) pixels)[my * imw + mx];

              int red = defaultRGB.getRed(pixel),
                  green = defaultRGB.getGreen(pixel),
                  blue = defaultRGB.getBlue(pixel),
                  alpha = defaultRGB.getAlpha(pixel);

              showStatus("red=" + red + " green=" + green + " blue=" + blue + " alpha=" + alpha);
            }
          }
        });
  }

  public void paint(Graphics g) {
    Insets insets = getInsets();
    g.drawImage(image, insets.left, insets.top, this);
  }
}
  // ///////////////////////////////////////////////////////////////
  // 双线性内插值算法
  // 参数:img:要缩放的Image对象
  // dstW:目标图像宽
  // dstH:目标图像高
  // comp:组件参数,比如Applet
  //
  // 公式:f(i+u,j+v) = (1-u)(1-v)f(i,j) + (1-u)vf(i,j+1) + u(1-v)f(i+1,j) +
  // uvf(i+1,j+1)
  //
  // ///////////////////////////////////////////////////////////////
  public static Image doubleLinearScale(Image img, int dstW, int dstH) {
    OperateImage OI = new OperateImage();
    Image imgTemp;
    int[] scaled, src;
    int srcW, srcH;
    int R, G, B;
    double widthFactor, heightFactor, tempX, tempY;
    // double srcX_float = 0.0, srcY_float = 0.0;// 坐标的小数部分
    // int srcX_int = 0, srcY_int = 0;// 坐标的整数部分
    src = OI.takeImg(img, img.getWidth(null), img.getHeight(null));
    ColorModel cm = ColorModel.getRGBdefault();
    for (int j = 0; j < src.length; j++) {
      R = cm.getRed(src[j]);
      G = cm.getGreen(src[j]);
      B = cm.getBlue(src[j]);
      if (R >= 200 && G >= 200 && B >= 200) src[j] = 0xffffffff;
      else src[j] = 0xff000000;
    }
    scaled = new int[dstW * dstH]; // 存放缩放后的图片
    srcW = img.getWidth(null);
    srcH = img.getHeight(null);

    widthFactor = srcW / (dstW + 0.0);
    // System.out.println("widthFactor:"+widthFactor);
    heightFactor = srcH / (dstH + 0.0);
    // System.out.println("heightFactor:"+heightFactor);
    for (int a = 0; a < dstH; a++)
      for (int b = 0; b < dstW; b++) {
        tempX = b * widthFactor;
        tempY = a * heightFactor;
        scaled[a * dstW + b] = getDestPixle(src, srcW, srcH, tempX, tempY);
      }
    // System.out.println("双线性内插值算法完成!");
    imgTemp = OI.madeImg(scaled, dstW, dstH);
    ImageFilter filter = new BWFilter();
    return Toolkit.getDefaultToolkit()
        .createImage(new FilteredImageSource(imgTemp.getSource(), filter));
    // return imgTemp;
  }
  /**
   * PS see http://astronomy.swin.edu.au/~pbourke/geomformats/postscript/ Java
   * http://show.docjava.com:8086/book/cgij/doc/ip/graphics/SimpleImageFrame.java.html
   */
  public boolean drawImage(
      Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) {
    try {
      // get data from image
      int[] pixels = new int[width * height];
      PixelGrabber grabber = new PixelGrabber(img, 0, 0, width, height, pixels, 0, width);
      grabber.grabPixels();
      ColorModel model = ColorModel.getRGBdefault();

      // print data to ps
      m_printstream.println("gsave");
      m_printstream.println(
          xTransform(xScale(x)) + " " + (yTransform(yScale(y)) - yScale(height)) + " translate");
      m_printstream.println(xScale(width) + " " + yScale(height) + " scale");
      m_printstream.println(
          width + " " + height + " " + "8" + " [" + width + " 0 0 " + (-height) + " 0 " + height
              + "]");
      m_printstream.println("{<");

      int index;
      for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
          index = i * width + j;
          m_printstream.print(toHex(model.getRed(pixels[index])));
          m_printstream.print(toHex(model.getGreen(pixels[index])));
          m_printstream.print(toHex(model.getBlue(pixels[index])));
        }
        m_printstream.println();
      }

      m_printstream.println(">}");
      m_printstream.println("false 3 colorimage");
      m_printstream.println("grestore");
      return true;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
  public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) {
    Rectangle2D newBounds = getBounds2D(src);

    // Destination image should include (0,0) + positive part
    // of the area bounded by newBounds (in source coordinate system).
    double dstWidth = newBounds.getX() + newBounds.getWidth();
    double dstHeight = newBounds.getY() + newBounds.getHeight();

    if (dstWidth <= 0 || dstHeight <= 0) {
      // awt.251=Transformed width ({0}) and height ({1}) should be
      // greater than 0
      throw new RasterFormatException(
          Messages.getString("awt.251", dstWidth, dstHeight)); // $NON-NLS-1$
    }

    if (destCM != null) {
      return new BufferedImage(
          destCM,
          destCM.createCompatibleWritableRaster((int) dstWidth, (int) dstHeight),
          destCM.isAlphaPremultiplied(),
          null);
    }

    ColorModel cm = src.getColorModel();

    // Interpolation other than NN doesn't make any sense for index color
    if (iType != TYPE_NEAREST_NEIGHBOR && cm instanceof IndexColorModel) {
      return new BufferedImage((int) dstWidth, (int) dstHeight, BufferedImage.TYPE_INT_ARGB);
    }

    // OK, we can get source color model
    return new BufferedImage(
        cm,
        src.getRaster().createCompatibleWritableRaster((int) dstWidth, (int) dstHeight),
        cm.isAlphaPremultiplied(),
        null);
  }
Exemple #12
0
  public static void main(String args[]) {
    try {
      ICC_Profile inProfile =
          ICC_Profile.getInstance("/System/Library/ColorSync/Profiles/AdobeRGB1998.icc");
      ICC_Profile outProfile =
          ICC_Profile.getInstance("/Library/ColorSync/Profiles/CIE 1931 D50 Gamma 1.icm");

      Profile cmsOutProfile = new Profile(outProfile);
      Profile cmsInProfile = new Profile(inProfile);

      BufferedImage inputImage = ImageIO.read(new File("/Stuff/Reference/small-q60-adobergb.TIF"));
      ShortInterleavedRaster inputRaster = (ShortInterleavedRaster) inputImage.getTile(0, 0);

      ColorSpace outCS = new ICC_ColorSpace(outProfile);
      ColorModel outCM =
          new ComponentColorModel(outCS, false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
      ShortInterleavedRaster outputRaster =
          (ShortInterleavedRaster)
              outCM.createCompatibleWritableRaster(inputImage.getWidth(), inputImage.getHeight());
      BufferedImage outputImage = new BufferedImage(outCM, outputRaster, false, null);

      Transform cmsTransform =
          new Transform(
              cmsInProfile, TYPE_RGB_16, cmsOutProfile, TYPE_RGB_16, INTENT_PERCEPTUAL, 0);

      cmsTransform.doTransform(inputRaster, outputRaster);

      ImageIO.write(outputImage, "TIF", new File("/Stuff/small-q60-CIED65.TIF"));

      cmsTransform.dispose();
      cmsOutProfile.dispose();
      cmsInProfile.dispose();
      // System.out.println("Profile: " + hProfile + ", " + );
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Paint the image onto a Graphics object. The painting is performed tile-by-tile, and includes a
   * grey region covering the unused portion of image tiles as well as the general background. At
   * this point the image must be byte data.
   */
  public synchronized void paintComponent(Graphics g) {

    Graphics2D g2D = null;
    if (g instanceof Graphics2D) {
      g2D = (Graphics2D) g;
    } else {
      return;
    }

    // if source is null, it's just a component
    if (source == null) {
      g2D.setColor(getBackground());
      g2D.fillRect(0, 0, componentWidth, componentHeight);
      return;
    }

    int transX = -originX;
    int transY = -originY;

    // Get the clipping rectangle and translate it into image coordinates.
    Rectangle clipBounds = g.getClipBounds();

    if (clipBounds == null) {
      clipBounds = new Rectangle(0, 0, componentWidth, componentHeight);
    }

    // clear the background (clip it) [minimal optimization here]
    if (transX > 0
        || transY > 0
        || transX < (componentWidth - source.getWidth())
        || transY < (componentHeight - source.getHeight())) {
      g2D.setColor(getBackground());
      g2D.fillRect(0, 0, componentWidth, componentHeight);
    }

    clipBounds.translate(-transX, -transY);

    // Determine the extent of the clipping region in tile coordinates.
    int txmin, txmax, tymin, tymax;
    int ti, tj;

    txmin = XtoTileX(clipBounds.x);
    txmin = Math.max(txmin, minTileX);
    txmin = Math.min(txmin, maxTileX);

    txmax = XtoTileX(clipBounds.x + clipBounds.width - 1);
    txmax = Math.max(txmax, minTileX);
    txmax = Math.min(txmax, maxTileX);

    tymin = YtoTileY(clipBounds.y);
    tymin = Math.max(tymin, minTileY);
    tymin = Math.min(tymin, maxTileY);

    tymax = YtoTileY(clipBounds.y + clipBounds.height - 1);
    tymax = Math.max(tymax, minTileY);
    tymax = Math.min(tymax, maxTileY);
    Insets insets = getInsets();

    // Loop over tiles within the clipping region
    for (tj = tymin; tj <= tymax; tj++) {
      for (ti = txmin; ti <= txmax; ti++) {
        int tx = TileXtoX(ti);
        int ty = TileYtoY(tj);

        Raster tile = source.getTile(ti, tj);
        if (tile != null) {
          DataBuffer dataBuffer = tile.getDataBuffer();

          WritableRaster wr = tile.createWritableRaster(sampleModel, dataBuffer, null);

          BufferedImage bi =
              new BufferedImage(colorModel, wr, colorModel.isAlphaPremultiplied(), null);

          // correctly handles band offsets
          if (brightnessEnabled == true) {
            SampleModel sm =
                sampleModel.createCompatibleSampleModel(tile.getWidth(), tile.getHeight());

            WritableRaster raster = RasterFactory.createWritableRaster(sm, null);

            BufferedImage bimg =
                new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

            // don't move this code
            ByteLookupTable lutTable = new ByteLookupTable(0, lutData);
            LookupOp lookup = new LookupOp(lutTable, null);
            lookup.filter(bi, bimg);

            g2D.drawImage(bimg, biop, tx + transX + insets.left, ty + transY + insets.top);
          } else {
            AffineTransform transform;

            transform =
                AffineTransform.getTranslateInstance(
                    tx + transX + insets.left, ty + transY + insets.top);

            g2D.drawRenderedImage(bi, transform);
          }
        }
      }
    }
  }
  @Override
  protected void computeRect(Raster[] sources, WritableRaster dest, Rectangle destRect) {
    synchronized (this) {
      if (transform == null) {
        int lcms_intent =
            intent.getValue() < 4 ? intent.getValue() : LCMS.INTENT_RELATIVE_COLORIMETRIC;
        int lcms_proofIntent =
            proofIntent.getValue() < 4 ? proofIntent.getValue() : LCMS.INTENT_RELATIVE_COLORIMETRIC;
        int lcms_flags =
            intent.getValue() == 4 || proofIntent.getValue() == 4
                ? LCMS.cmsFLAGS_BLACKPOINTCOMPENSATION
                : 0;

        ColorSpace sourceCS = source.getColorModel().getColorSpace();
        LCMS.Profile sourceProfile =
            sourceCS instanceof LCMS_ColorSpace
                ? ((LCMS_ColorSpace) sourceCS).getProfile()
                : new LCMS.Profile(((ICC_ColorSpace) sourceCS).getProfile());

        ColorSpace targetCS = targetColorModel.getColorSpace();
        LCMS.Profile targetProfile =
            targetCS instanceof LCMS_ColorSpace
                ? ((LCMS_ColorSpace) targetCS).getProfile()
                : new LCMS.Profile(((ICC_ColorSpace) targetCS).getProfile());

        LCMS.Profile proofProfile = proof != null ? new LCMS.Profile(proof) : null;

        int inType = mapLCMSType(sourceCS.getType(), source.getColorModel().getTransferType());
        int outType = mapLCMSType(targetCS.getType(), colorModel.getTransferType());

        transform =
            proofProfile != null
                ? new LCMS.Transform(
                    sourceProfile,
                    inType,
                    targetProfile,
                    outType,
                    proofProfile,
                    lcms_proofIntent,
                    lcms_intent,
                    lcms_flags)
                : new LCMS.Transform(
                    sourceProfile, inType, targetProfile, outType, lcms_intent, lcms_flags);
      }
    }

    RasterFormatTag[] formatTags = getFormatTags();
    Rectangle srcRect = mapDestRect(destRect, 0);
    RasterAccessor src =
        new RasterAccessor(sources[0], srcRect, formatTags[0], getSourceImage(0).getColorModel());
    RasterAccessor dst = new RasterAccessor(dest, destRect, formatTags[1], this.getColorModel());

    if (src.getDataType() == dst.getDataType()) {
      transform.doTransform(
          src,
          formatTags[0],
          getSourceImage(0).getColorModel(),
          dst,
          formatTags[1],
          this.getColorModel());
    } else {
      throw new IllegalArgumentException("Input and output rasters don't match!");
    }
  }
  public void actionPerformed(ActionEvent evt) {
    Graphics g = getGraphics();
    if (evt.getSource() == openItem) {
      JFileChooser chooser = new JFileChooser();
      common.chooseFile(chooser, "./images", 0); // 设置默认目录,过滤文件
      int r = chooser.showOpenDialog(null);

      if (r == JFileChooser.APPROVE_OPTION) {
        String name = chooser.getSelectedFile().getAbsolutePath();

        // 装载图像
        iImage = common.openImage(name, new MediaTracker(this));

        // 取载入图像的宽和高
        iw = iImage.getWidth(null);
        ih = iImage.getHeight(null);
        bImage = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bImage.createGraphics();
        g2.drawImage(iImage, 0, 0, null);
        loadflag = true;
        repaint();
      }
    } else if (evt.getSource() == rotateItem) // 内置旋转
    {
      setTitle("第4章 图像几何变换 内置旋转 作者 孙燮华");
      common.draw(g, iImage, bImage, common.getParam("旋转角(度):", "30"), 0, 0);
    } else if (evt.getSource() == scaleItem) // 内置缩放
    {
      setTitle("第4章 图像几何变换 内置缩放 作者 孙燮华");
      // 参数选择面板
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "1.5", "1.5");
      setPanel(pp, "内置缩放");
      float x = pp.getPadx();
      float y = pp.getPady();
      common.draw(g, iImage, bImage, x, y, 1);
    } else if (evt.getSource() == shearItem) // 内置错切
    {
      setTitle("第4章 图像几何变换 内置错切 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "0.5", "0.5");
      setPanel(pp, "内置错切");
      float x = pp.getPadx();
      float y = pp.getPady();
      common.draw(g, iImage, bImage, x, y, 2);
    } else if (evt.getSource() == transItem) // 内置平移
    {
      setTitle("第4章 图像几何变换 内置平移 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "100", "50");
      setPanel(pp, "内置平移");
      float x = pp.getPadx();
      float y = pp.getPady();
      common.draw(g, iImage, bImage, x, y, 3);
    } else if (evt.getSource() == rotItem) // 旋转算法
    {
      setTitle("第4章 图像几何变换 旋转算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      // 旋转,输出图像宽高
      int owh = (int) (Math.sqrt(iw * iw + ih * ih + 0.5));
      opix = geom.imRotate(pix, common.getParam("旋转角(度):", "30"), iw, ih, owh);

      // 将数组中的象素产生一个图像
      MemoryImageSource memoryImage =
          new MemoryImageSource(owh, owh, ColorModel.getRGBdefault(), opix, 0, owh);
      oImage = createImage(memoryImage);
      common.draw(g, iImage, oImage, iw, ih, owh, 4);
    } else if (evt.getSource() == mirItem) // 镜象算法(type:5)
    {
      setTitle("第4章 图像几何变换 镜象算法 作者 孙燮华");
      Parameters pp = new Parameters("选择镜象类型", "水平", "垂直");
      setPanel(pp, "镜象算法");

      pix = common.grabber(iImage, iw, ih);
      opix = geom.imMirror(pix, iw, ih, pp.getRadioState());
      ImageProducer ip = new MemoryImageSource(iw, ih, opix, 0, iw);
      oImage = createImage(ip);
      common.draw(g, iImage, oImage, iw, ih, 0, 5);
    } else if (evt.getSource() == shrItem) // 错切算法(type:6)
    {
      setTitle("第4章 图像几何变换 错切算法 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "0.5", "0.5");
      setPanel(pp, "错切算法");

      pix = common.grabber(iImage, iw, ih);

      float shx = pp.getPadx();
      float shy = pp.getPady();

      // 计算包围盒的宽和高
      int ow = (int) (iw + (ih - 1) * shx);
      int oh = (int) ((iw - 1) * shy + ih);

      if (shx > 0 && shy > 0) {
        opix = geom.imShear(pix, shx, shy, iw, ih, ow, oh);
        ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
        oImage = createImage(ip);
        common.draw(g, iImage, oImage, iw, ih, 0, 6);
      } else JOptionPane.showMessageDialog(null, "参数必须为正数!");
    } else if (evt.getSource() == trnItem) {
      setTitle("第4章 图像几何变换 平移算法 作者 孙燮华");
      Parameters pp = new Parameters("参数", "x方向:", "y方向:", "100", "50");
      setPanel(pp, "平移算法");
      pix = common.grabber(iImage, iw, ih);
      int tx = (int) pp.getPadx();
      int ty = (int) pp.getPady();

      if (tx > 0 && ty > 0) {
        int ow = iw + tx;
        int oh = ih + ty;
        opix = geom.imTrans(pix, tx, ty, iw, ih, ow, oh);
        ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
        oImage = createImage(ip);
        common.draw(g, iImage, oImage, iw, ih, 0, 7);
      } else JOptionPane.showMessageDialog(null, "参数必须为正数!");
    } else if (evt.getSource() == nearItem) {
      setTitle("第4章 图像几何变换 最邻近插值算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      float p =
          (Float.valueOf(JOptionPane.showInputDialog(null, "输入缩放参数(0.1-3.0)", "1.50")))
              .floatValue();
      int ow = (int) (p * iw); // 计算目标图宽高
      int oh = (int) (p * ih);
      opix = geom.nearNeighbor(pix, iw, ih, ow, oh, p);
      ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
      oImage = createImage(ip);
      common.draw(g, oImage, "最邻近插值", p);
    } else if (evt.getSource() == linrItem) {
      setTitle("第4章 图像几何变换 双线性插值算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      float p =
          (Float.valueOf(JOptionPane.showInputDialog(null, "输入缩放参数(0.1-3.0)", "1.50")))
              .floatValue();
      int ow = (int) (p * iw); // 计算目标图宽高
      int oh = (int) (p * ih);
      opix = geom.bilinear(pix, iw, ih, ow, oh, p);
      ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
      oImage = createImage(ip);
      common.draw(g, oImage, "双线性插值", p);
    } else if (evt.getSource() == cubicItem) {
      setTitle("第4章 图像几何变换 三次卷积插值算法 作者 孙燮华");
      pix = common.grabber(iImage, iw, ih);

      float p =
          (Float.valueOf(JOptionPane.showInputDialog(null, "输入缩放参数(1.1-3.0)", "1.50")))
              .floatValue();
      if (p < 1) {
        JOptionPane.showMessageDialog(null, "参数p必须大于1!");
        return;
      }
      int ow = (int) (p * iw); // 计算目标图宽高
      int oh = (int) (p * ih);
      opix = geom.scale(pix, iw, ih, ow, oh, p, p);
      ImageProducer ip = new MemoryImageSource(ow, oh, opix, 0, ow);
      oImage = createImage(ip);
      common.draw(g, oImage, "三次卷积插值", p);
    } else if (evt.getSource() == okButton) dialog.dispose();
    else if (evt.getSource() == exitItem) System.exit(0);
  }
  private void readHeader() throws IOException {
    if (gotHeader) {
      iis.seek(128);
      return;
    }

    metadata = new PCXMetadata();

    manufacturer = iis.readByte(); // manufacturer
    if (manufacturer != MANUFACTURER) throw new IllegalStateException("image is not a PCX file");
    metadata.version = iis.readByte(); // version
    encoding = iis.readByte(); // encoding
    if (encoding != ENCODING)
      throw new IllegalStateException("image is not a PCX file, invalid encoding " + encoding);

    metadata.bitsPerPixel = iis.readByte();

    metadata.xmin = iis.readShort();
    metadata.ymin = iis.readShort();
    xmax = iis.readShort();
    ymax = iis.readShort();

    metadata.hdpi = iis.readShort();
    metadata.vdpi = iis.readShort();

    iis.readFully(smallPalette);

    iis.readByte(); // reserved

    colorPlanes = iis.readByte();
    bytesPerLine = iis.readShort();
    paletteType = iis.readShort();

    metadata.hsize = iis.readShort();
    metadata.vsize = iis.readShort();

    iis.skipBytes(54); // skip filler

    width = xmax - metadata.xmin + 1;
    height = ymax - metadata.ymin + 1;

    if (colorPlanes == 1) {
      if (paletteType == PALETTE_GRAYSCALE) {
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        int[] nBits = {8};
        colorModel =
            new ComponentColorModel(
                cs, nBits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
        sampleModel =
            new ComponentSampleModel(DataBuffer.TYPE_BYTE, width, height, 1, width, new int[] {0});
      } else {
        if (metadata.bitsPerPixel == 8) {
          // read palette from end of file, then reset back to image data
          iis.mark();

          if (iis.length() == -1) {
            // read until eof, and work backwards
            while (iis.read() != -1) ;
            iis.seek(iis.getStreamPosition() - 256 * 3 - 1);
          } else {
            iis.seek(iis.length() - 256 * 3 - 1);
          }

          int palletteMagic = iis.read();
          if (palletteMagic != 12)
            processWarningOccurred(
                "Expected palette magic number 12; instead read "
                    + palletteMagic
                    + " from this image.");

          iis.readFully(largePalette);
          iis.reset();

          colorModel = new IndexColorModel(metadata.bitsPerPixel, 256, largePalette, 0, false);
          sampleModel = colorModel.createCompatibleSampleModel(width, height);
        } else {
          int msize = metadata.bitsPerPixel == 1 ? 2 : 16;
          colorModel = new IndexColorModel(metadata.bitsPerPixel, msize, smallPalette, 0, false);
          sampleModel = colorModel.createCompatibleSampleModel(width, height);
        }
      }
    } else {
      ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
      int[] nBits = {8, 8, 8};
      colorModel =
          new ComponentColorModel(
              cs, nBits, false, false, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
      sampleModel =
          new ComponentSampleModel(
              DataBuffer.TYPE_BYTE,
              width,
              height,
              1,
              width * colorPlanes,
              new int[] {0, width, width * 2});
    }

    originalSampleModel = sampleModel;
    originalColorModel = colorModel;

    gotHeader = true;
  }
 @Override
 public Color compute(double x, double y) {
   return model.compute(
       x * Math.cos(angle) - y * Math.sin(angle), x * Math.sin(angle) + y * Math.cos(angle));
 }
  public BufferedImage filter(BufferedImage src, BufferedImage dst) {
    int width = src.getWidth();
    int height = src.getHeight();
    int type = src.getType();
    WritableRaster srcRaster = src.getRaster();

    originalSpace = new Rectangle(0, 0, width, height);
    transformedSpace = new Rectangle(0, 0, width, height);
    transformSpace(transformedSpace);

    if (dst == null) {
      ColorModel dstCM = src.getColorModel();
      dst =
          new BufferedImage(
              dstCM,
              dstCM.createCompatibleWritableRaster(transformedSpace.width, transformedSpace.height),
              dstCM.isAlphaPremultiplied(),
              null);
    }
    WritableRaster dstRaster = dst.getRaster();

    int[] inPixels = getRGB(src, 0, 0, width, height, null);

    if (interpolation == NEAREST_NEIGHBOUR)
      return filterPixelsNN(dst, width, height, inPixels, transformedSpace);

    int srcWidth = width;
    int srcHeight = height;
    int srcWidth1 = width - 1;
    int srcHeight1 = height - 1;
    int outWidth = transformedSpace.width;
    int outHeight = transformedSpace.height;
    int outX, outY;
    int index = 0;
    int[] outPixels = new int[outWidth];

    outX = transformedSpace.x;
    outY = transformedSpace.y;
    float[] out = new float[2];

    for (int y = 0; y < outHeight; y++) {
      for (int x = 0; x < outWidth; x++) {
        transformInverse(outX + x, outY + y, out);
        int srcX = (int) Math.floor(out[0]);
        int srcY = (int) Math.floor(out[1]);
        float xWeight = out[0] - srcX;
        float yWeight = out[1] - srcY;
        int nw, ne, sw, se;

        if (srcX >= 0 && srcX < srcWidth1 && srcY >= 0 && srcY < srcHeight1) {
          // Easy case, all corners are in the image
          int i = srcWidth * srcY + srcX;
          nw = inPixels[i];
          ne = inPixels[i + 1];
          sw = inPixels[i + srcWidth];
          se = inPixels[i + srcWidth + 1];
        } else {
          // Some of the corners are off the image
          nw = getPixel(inPixels, srcX, srcY, srcWidth, srcHeight);
          ne = getPixel(inPixels, srcX + 1, srcY, srcWidth, srcHeight);
          sw = getPixel(inPixels, srcX, srcY + 1, srcWidth, srcHeight);
          se = getPixel(inPixels, srcX + 1, srcY + 1, srcWidth, srcHeight);
        }
        outPixels[x] = ImageMath.bilinearInterpolate(xWeight, yWeight, nw, ne, sw, se);
      }
      setRGB(dst, 0, y, transformedSpace.width, 1, outPixels);
    }
    return dst;
  }
  public BufferedImage decompress(final QuickTime.ImageDesc pDescription, final InputStream pStream)
      throws IOException {
    byte[] data = new byte[pDescription.dataSize];

    DataInputStream stream = new DataInputStream(pStream);
    try {
      stream.readFully(data, 0, pDescription.dataSize);
    } finally {
      stream.close();
    }

    DataBuffer buffer = new DataBufferByte(data, data.length);

    WritableRaster raster;

    // TODO: Depth parameter can be 1-32 (color) or 33-40 (gray scale)
    switch (pDescription.depth) {
      case 40: // 8 bit gray (untested)
        raster =
            Raster.createInterleavedRaster(
                buffer,
                pDescription.width,
                pDescription.height,
                pDescription.width,
                1,
                new int[] {0},
                null);
        break;
      case 24: // 24 bit RGB
        raster =
            Raster.createInterleavedRaster(
                buffer,
                pDescription.width,
                pDescription.height,
                pDescription.width * 3,
                3,
                new int[] {0, 1, 2},
                null);
        break;
      case 32: // 32 bit ARGB
        // WORKAROUND: There is a bug in the way Java 2D interprets the band offsets in
        // Raster.createInterleavedRaster (see below) before Java 6. So, instead of
        // passing a correct offset array below, we swap channel 1 & 3 to make it ABGR...
        for (int y = 0; y < pDescription.height; y++) {
          for (int x = 0; x < pDescription.width; x++) {
            int offset = 4 * y * pDescription.width + x * 4;
            byte temp = data[offset + 1];
            data[offset + 1] = data[offset + 3];
            data[offset + 3] = temp;
          }
        }

        raster =
            Raster.createInterleavedRaster(
                buffer,
                pDescription.width,
                pDescription.height,
                pDescription.width * 4,
                4,
                new int[] {3, 2, 1, 0}, // B & R mixed up. {1, 2, 3, 0} is correct
                null);
        break;
      default:
        throw new IIOException("Unsupported RAW depth: " + pDescription.depth);
    }

    ColorModel cm =
        new ComponentColorModel(
            pDescription.depth <= 32
                ? ColorSpace.getInstance(ColorSpace.CS_sRGB)
                : ColorSpace.getInstance(ColorSpace.CS_GRAY),
            pDescription.depth == 32,
            false,
            pDescription.depth == 32 ? Transparency.TRANSLUCENT : Transparency.OPAQUE,
            DataBuffer.TYPE_BYTE);

    return new BufferedImage(cm, raster, cm.isAlphaPremultiplied(), null);
  }
Exemple #20
0
    public int[] doContrast(int[] pix, int iw, int ih, double contrast)
    {    
		ColorModel cm = ColorModel.getRGBdefault();
		int r, g, b;
		for(int i = 0; i < iw*ih; i++)	
		{			
			r = (int) (contrast>=0?cm.getRed(pix[i]) + (255-cm.getRed(pix[i]))*contrast:
				cm.getRed(pix[i]) + cm.getRed(pix[i])*contrast);
			g = (int) (contrast>=0?cm.getGreen(pix[i]) + (255-cm.getGreen(pix[i]))*contrast:
				cm.getGreen(pix[i]) + cm.getGreen(pix[i])*contrast);
			b = (int) (contrast>=0?cm.getBlue(pix[i]) + (255-cm.getBlue(pix[i]))*contrast:
				cm.getBlue(pix[i]) + cm.getBlue(pix[i])*contrast);
	
			pix[i] = 255 << 24|r << 16|g << 8|b;
			
		}
		System.out.println("contrast is: " + contrast);
		return pix;
	}