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; }
private static CharSequence recreateView( String text, int caret, int selectionLength, boolean hasFocus, Highlighter... highlighters) { StringBuilder sb = new StringBuilder(); sb.append("<pre>"); ColorModel colorModel = new ColorModel(text.length() + 1); for (Highlighter highlighter : highlighters) { highlighter.highlight(text, caret, selectionLength, hasFocus, colorModel); } if (hasFocus) { if (selectionLength != 0) { colorModel.addStyle(caret, caret + selectionLength, "sel"); } else { colorModel.addStyle(caret, "caret"); } } for (int i = 0; i <= text.length(); ) { int next = colorModel.getNextDifferent(i); CharSequence style = colorModel.getStyle(i); if (style != null) { sb.append("<span class='").append(style).append("'>"); } if (next == text.length() + 1) { sb.append(text, i, text.length()); sb.append(" "); } else { sb.append(text, i, next); } if (style != null) { sb.append("</span>"); } i = next; } sb.append("</pre>"); return sb; }
/** * 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; }
public static boolean compressPic(String srcFilePath, String descFilePath) { File file = null; BufferedImage src = null; FileOutputStream out = null; ImageWriter imgWrier; ImageWriteParam imgWriteParams; // 指定写图片的方式为 jpg imgWrier = ImageIO.getImageWritersByFormatName("jpg").next(); imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null); // 要使用压缩,必须指定压缩方式为MODE_EXPLICIT imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT); // 这里指定压缩的程度,参数qality是取值0~1范围内, imgWriteParams.setCompressionQuality((float) 0.1); imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED); ColorModel colorModel = ColorModel.getRGBdefault(); // 指定压缩时使用的色彩模式 imgWriteParams.setDestinationType( new javax.imageio.ImageTypeSpecifier( colorModel, colorModel.createCompatibleSampleModel(16, 16))); try { if (StringUtils.isBlank(srcFilePath)) { return false; } else { file = new File(srcFilePath); src = ImageIO.read(file); out = new FileOutputStream(descFilePath); imgWrier.reset(); // 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何 OutputStream构造 imgWrier.setOutput(ImageIO.createImageOutputStream(out)); // 调用write方法,就可以向输入流写图片 imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams); out.flush(); out.close(); } } catch (Exception e) { e.printStackTrace(); return false; } return true; }
// 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(); }
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; }
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; } }
/** * Filters the information provided in the <code>imageComplete</code> method of the <code> * ImageConsumer</code> interface. * * <p>Note: This method is intended to be called by the <code>ImageProducer</code> of the <code> * Image</code> whose pixels are being filtered. Developers using this class to retrieve pixels * from an image should avoid calling this method directly since that operation could result in * problems with retrieving the requested pixels. * * @param status the status of image loading * @throws ImagingOpException if there was a problem calling the filter method of the <code> * BufferedImageOp</code> associated with this instance. * @see ImageConsumer#imageComplete */ public void imageComplete(int status) { WritableRaster wr; switch (status) { case IMAGEERROR: case IMAGEABORTED: // reinitialize the params model = null; width = -1; height = -1; intPixels = null; bytePixels = null; break; case SINGLEFRAMEDONE: case STATICIMAGEDONE: if (width <= 0 || height <= 0) break; if (model instanceof DirectColorModel) { if (intPixels == null) break; wr = createDCMraster(); } else if (model instanceof IndexColorModel) { int[] bandOffsets = {0}; if (bytePixels == null) break; DataBufferByte db = new DataBufferByte(bytePixels, width * height); wr = Raster.createInterleavedRaster(db, width, height, width, 1, bandOffsets, null); } else { convertToRGB(); if (intPixels == null) break; wr = createDCMraster(); } BufferedImage bi = new BufferedImage(model, wr, model.isAlphaPremultiplied(), null); bi = bufferedImageOp.filter(bi, null); WritableRaster r = bi.getRaster(); ColorModel cm = bi.getColorModel(); int w = r.getWidth(); int h = r.getHeight(); consumer.setDimensions(w, h); consumer.setColorModel(cm); if (cm instanceof DirectColorModel) { DataBufferInt db = (DataBufferInt) r.getDataBuffer(); consumer.setPixels(0, 0, w, h, cm, db.getData(), 0, w); } else if (cm instanceof IndexColorModel) { DataBufferByte db = (DataBufferByte) r.getDataBuffer(); consumer.setPixels(0, 0, w, h, cm, db.getData(), 0, w); } else { throw new InternalError("Unknown color model " + cm); } break; } consumer.imageComplete(status); }
/** * {@collect.stats} Creates a zeroed destination image with the correct size and number of bands. * * @param src Source image for the filter operation. * @param destCM ColorModel of the destination. If null, the ColorModel of the source will be * used. * @return the zeroed-destination image. */ public BufferedImage createCompatibleDestImage(BufferedImage src, ColorModel destCM) { BufferedImage image; if (destCM == null) { ColorModel cm = src.getColorModel(); image = new BufferedImage( cm, src.getRaster().createCompatibleWritableRaster(), cm.isAlphaPremultiplied(), null); } else { int w = src.getWidth(); int h = src.getHeight(); image = new BufferedImage( destCM, destCM.createCompatibleWritableRaster(w, h), destCM.isAlphaPremultiplied(), null); } return image; }
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); }
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(); } }
private final WritableRaster createDCMraster() { WritableRaster wr; DirectColorModel dcm = (DirectColorModel) model; boolean hasAlpha = model.hasAlpha(); int[] bandMasks = new int[3 + (hasAlpha ? 1 : 0)]; bandMasks[0] = dcm.getRedMask(); bandMasks[1] = dcm.getGreenMask(); bandMasks[2] = dcm.getBlueMask(); if (hasAlpha) { bandMasks[3] = dcm.getAlphaMask(); } DataBufferInt db = new DataBufferInt(intPixels, width * height); wr = Raster.createPackedRaster(db, width, height, width, bandMasks, null); return wr; }
private void convertToRGB() { int size = width * height; int newpixels[] = new int[size]; if (bytePixels != null) { for (int i = 0; i < size; i++) { newpixels[i] = this.model.getRGB(bytePixels[i] & 0xff); } } else if (intPixels != null) { for (int i = 0; i < size; i++) { newpixels[i] = this.model.getRGB(intPixels[i]); } } bytePixels = null; intPixels = newpixels; this.model = ColorModel.getRGBdefault(); }
static { ColorModel.loadLibraries(); initIDs(); }
public void write(BufferedImage image, AVList params) throws IOException { if (image == null) { String msg = Logging.getMessage("nullValue.ImageSource"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (0 == image.getWidth() || 0 == image.getHeight()) { String msg = Logging.getMessage("generic.InvalidImageSize", image.getWidth(), image.getHeight()); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (null == params || 0 == params.getValues().size()) { String reason = Logging.getMessage("nullValue.AVListIsNull"); Logging.logger().finest(Logging.getMessage("GeotiffWriter.GeoKeysMissing", reason)); params = new AVListImpl(); } else { this.validateParameters(params, image.getWidth(), image.getHeight()); } // how we proceed in part depends upon the image type... int type = image.getType(); // handle CUSTOM type which comes from our GeoTiffreader (for now) if (BufferedImage.TYPE_CUSTOM == type) { int numColorComponents = 0, numComponents = 0, pixelSize = 0, dataType = 0, csType = 0; boolean hasAlpha = false; if (null != image.getColorModel()) { ColorModel cm = image.getColorModel(); numColorComponents = cm.getNumColorComponents(); numComponents = cm.getNumComponents(); pixelSize = cm.getPixelSize(); hasAlpha = cm.hasAlpha(); ColorSpace cs = cm.getColorSpace(); if (null != cs) csType = cs.getType(); } if (null != image.getSampleModel()) { SampleModel sm = image.getSampleModel(); dataType = sm.getDataType(); } if (dataType == DataBuffer.TYPE_FLOAT && pixelSize == Float.SIZE && numComponents == 1) { type = BufferedImage_TYPE_ELEVATION_FLOAT32; } else if (dataType == DataBuffer.TYPE_SHORT && pixelSize == Short.SIZE && numComponents == 1) { type = BufferedImage_TYPE_ELEVATION_SHORT16; } else if (ColorSpace.CS_GRAY == csType && pixelSize == Byte.SIZE) { type = BufferedImage.TYPE_BYTE_GRAY; } else if (dataType == DataBuffer.TYPE_USHORT && ColorSpace.CS_GRAY == csType && pixelSize == Short.SIZE) { type = BufferedImage.TYPE_USHORT_GRAY; } else if (ColorSpace.TYPE_RGB == csType && pixelSize == 3 * Byte.SIZE && numColorComponents == 3) { type = BufferedImage.TYPE_3BYTE_BGR; } else if (ColorSpace.TYPE_RGB == csType && hasAlpha && pixelSize == 4 * Byte.SIZE && numComponents == 4) { type = BufferedImage.TYPE_4BYTE_ABGR; } } switch (type) { case BufferedImage.TYPE_3BYTE_BGR: case BufferedImage.TYPE_4BYTE_ABGR: case BufferedImage.TYPE_4BYTE_ABGR_PRE: case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_INT_BGR: case BufferedImage.TYPE_INT_ARGB: case BufferedImage.TYPE_INT_ARGB_PRE: { this.writeColorImage(image, params); } break; case BufferedImage.TYPE_USHORT_GRAY: case BufferedImage.TYPE_BYTE_GRAY: { this.writeGrayscaleImage(image, params); } break; case BufferedImage_TYPE_ELEVATION_SHORT16: case BufferedImage_TYPE_ELEVATION_FLOAT32: { String msg = Logging.getMessage("GeotiffWriter.FeatureNotImplementedd", type); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } // break; case BufferedImage.TYPE_CUSTOM: default: { ColorModel cm = image.getColorModel(); SampleModel sm = image.getSampleModel(); StringBuffer sb = new StringBuffer(Logging.getMessage("GeotiffWriter.UnsupportedType", type)); sb.append("\n"); sb.append("NumBands=").append(sm.getNumBands()).append("\n"); sb.append("NumDataElements=").append(sm.getNumDataElements()).append("\n"); sb.append("NumColorComponents=").append(cm.getNumColorComponents()).append("\n"); sb.append("NumComponents=").append(cm.getNumComponents()).append("\n"); sb.append("PixelSize=").append(cm.getPixelSize()).append("\n"); sb.append("hasAlpha=").append(cm.hasAlpha()); String msg = sb.toString(); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } } }
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); }
public static void main(String args[]) { ColorModel cm = new ColorModel(32) { public int getAlpha(int pixel) { return 255; } public int getBlue(int pixel) { return 255; } public int getGreen(int pixel) { return 255; } public int getRed(int pixel) { return 255; } }; cm.hasAlpha(); cm.isAlphaPremultiplied(); cm.getTransferType(); cm.getPixelSize(); cm.getComponentSize(); cm.getComponentSize(); cm.getTransparency(); cm.getNumComponents(); cm.getNumColorComponents(); cm.getRed(20); cm.getGreen(20); cm.getBlue(20); cm.getAlpha(20); cm.getRGB(20); cm.isAlphaPremultiplied(); cm.isAlphaPremultiplied(); cm = ColorModel.getRGBdefault(); }
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); }
/* this is changed public void run() { */ public void produceImage() throws IOException, ImageFormatException { /* this is not needed ImageConsumer t = target; if(t!=null) try { */ try { for (int i = 0; i < signature.length; i++) if ((signature[i] & 0xFF) != underlyingInputStream.read()) throw new PNGException("Chunk signature mismatch"); InputStream is = new BufferedInputStream(new InflaterInputStream(inputStream, new Inflater())); getData(); byte[] bPixels = null; int[] wPixels = null; int pixSize = width; int rowStride; int logDepth = 0; switch (bitDepth) { case 1: logDepth = 0; break; case 2: logDepth = 1; break; case 4: logDepth = 2; break; case 8: logDepth = 3; break; case 16: logDepth = 4; break; default: throw new PNGException("invalid depth"); } if (interlaceMethod != 0) { pixSize *= height; rowStride = width; } else rowStride = 0; int combinedType = colorType | (bitDepth << 3); int bitMask = (1 << (bitDepth >= 8 ? 8 : bitDepth)) - 1; // Figure out the color model switch (colorType) { case COLOR | PALETTE: case COLOR | PALETTE | ALPHA: if (red_map == null) throw new PNGException("palette expected"); if (alpha_map == null) cm = new IndexColorModel(bitDepth, red_map.length, red_map, green_map, blue_map); else cm = new IndexColorModel( bitDepth, red_map.length, red_map, green_map, blue_map, alpha_map); bPixels = new byte[pixSize]; break; case GRAY: { int llog = logDepth >= 4 ? 3 : logDepth; if ((cm = greyModels[llog]) == null) { int size = 1 << (1 << llog); byte ramp[] = new byte[size]; for (int i = 0; i < size; i++) ramp[i] = (byte) (255 * i / (size - 1)); if (transparentPixel == -1) { cm = new IndexColorModel(bitDepth, ramp.length, ramp, ramp, ramp); } else { cm = new IndexColorModel( bitDepth, ramp.length, ramp, ramp, ramp, (transparentPixel & 0xFF)); } greyModels[llog] = cm; } } bPixels = new byte[pixSize]; break; case COLOR: case COLOR | ALPHA: case GRAY | ALPHA: cm = ColorModel.getRGBdefault(); wPixels = new int[pixSize]; break; default: throw new PNGException("invalid color type"); } /* this is going to be set in the pixel store t.setColorModel(cm); t.setHints(interlaceMethod !=0 ? ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES : ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | ImageConsumer.SINGLEPASS | ImageConsumer.SINGLEFRAME); */ // code added to make it work with ImageDecoder architecture setDimensions(width, height); setColorModel(cm); int flags = (interlaceMethod != 0 ? ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES : ImageConsumer.TOPDOWNLEFTRIGHT | ImageConsumer.COMPLETESCANLINES | ImageConsumer.SINGLEPASS | ImageConsumer.SINGLEFRAME); setHints(flags); headerComplete(); // end of adding int samplesPerPixel = ((colorType & PALETTE) != 0 ? 1 : ((colorType & COLOR) != 0 ? 3 : 1) + ((colorType & ALPHA) != 0 ? 1 : 0)); int bitsPerPixel = samplesPerPixel * bitDepth; int bytesPerPixel = (bitsPerPixel + 7) >> 3; int pass, passLimit; if (interlaceMethod == 0) { pass = -1; passLimit = 0; } else { pass = 0; passLimit = 7; } // These loops are far from being tuned. They're this way to make them easy to // debug. Tuning comes later. /* code changed. target not needed here while(++pass<=passLimit && (t=target)!=null) { */ while (++pass <= passLimit) { int row = startingRow[pass]; int rowInc = rowIncrement[pass]; int colInc = colIncrement[pass]; int bWidth = blockWidth[pass]; int bHeight = blockHeight[pass]; int sCol = startingCol[pass]; int rowPixelWidth = (width - sCol + (colInc - 1)) / colInc; int rowByteWidth = ((rowPixelWidth * bitsPerPixel) + 7) >> 3; if (rowByteWidth == 0) continue; int pixelBufferInc = interlaceMethod == 0 ? rowInc * width : 0; int rowOffset = rowStride * row; boolean firstRow = true; byte[] rowByteBuffer = new byte[rowByteWidth]; byte[] prevRowByteBuffer = new byte[rowByteWidth]; /* code changed. target not needed here while (row < height && (t=target)!=null) { */ while (row < height) { int rowFilter = is.read(); for (int rowFillPos = 0; rowFillPos < rowByteWidth; ) { int n = is.read(rowByteBuffer, rowFillPos, rowByteWidth - rowFillPos); if (n <= 0) throw new PNGException("missing data"); rowFillPos += n; } filterRow( rowByteBuffer, firstRow ? null : prevRowByteBuffer, rowFilter, rowByteWidth, bytesPerPixel); int col = sCol; int spos = 0; int pixel = 0; while (col < width) { if (wPixels != null) { switch (combinedType) { case COLOR | ALPHA | (8 << 3): wPixels[col + rowOffset] = ((rowByteBuffer[spos] & 0xFF) << 16) | ((rowByteBuffer[spos + 1] & 0xFF) << 8) | ((rowByteBuffer[spos + 2] & 0xFF)) | ((rowByteBuffer[spos + 3] & 0xFF) << 24); spos += 4; break; case COLOR | ALPHA | (16 << 3): wPixels[col + rowOffset] = ((rowByteBuffer[spos] & 0xFF) << 16) | ((rowByteBuffer[spos + 2] & 0xFF) << 8) | ((rowByteBuffer[spos + 4] & 0xFF)) | ((rowByteBuffer[spos + 6] & 0xFF) << 24); spos += 8; break; case COLOR | (8 << 3): pixel = ((rowByteBuffer[spos] & 0xFF) << 16) | ((rowByteBuffer[spos + 1] & 0xFF) << 8) | ((rowByteBuffer[spos + 2] & 0xFF)); if (pixel != transparentPixel) { pixel |= 0xff000000; } wPixels[col + rowOffset] = pixel; spos += 3; break; case COLOR | (16 << 3): pixel = ((rowByteBuffer[spos] & 0xFF) << 16) | ((rowByteBuffer[spos + 2] & 0xFF) << 8) | ((rowByteBuffer[spos + 4] & 0xFF)); boolean isTransparent = (transparentPixel_16 != null); for (int i = 0; isTransparent && (i < 6); i++) { isTransparent &= (rowByteBuffer[spos + i] & 0xFF) == (transparentPixel_16[i] & 0xFF); } if (!isTransparent) { pixel |= 0xff000000; } wPixels[col + rowOffset] = pixel; spos += 6; break; case GRAY | ALPHA | (8 << 3): { int tx = rowByteBuffer[spos] & 0xFF; wPixels[col + rowOffset] = (tx << 16) | (tx << 8) | tx | ((rowByteBuffer[spos + 1] & 0xFF) << 24); } spos += 2; break; case GRAY | ALPHA | (16 << 3): { int tx = rowByteBuffer[spos] & 0xFF; wPixels[col + rowOffset] = (tx << 16) | (tx << 8) | tx | ((rowByteBuffer[spos + 2] & 0xFF) << 24); } spos += 4; break; default: throw new PNGException("illegal type/depth"); } } else switch (bitDepth) { case 1: bPixels[col + rowOffset] = (byte) ((rowByteBuffer[spos >> 3] >> (7 - (spos & 7))) & 1); spos++; break; case 2: bPixels[col + rowOffset] = (byte) ((rowByteBuffer[spos >> 2] >> ((3 - (spos & 3)) * 2)) & 3); spos++; break; case 4: bPixels[col + rowOffset] = (byte) ((rowByteBuffer[spos >> 1] >> ((1 - (spos & 1)) * 4)) & 15); spos++; break; case 8: bPixels[col + rowOffset] = rowByteBuffer[spos++]; break; case 16: bPixels[col + rowOffset] = rowByteBuffer[spos]; spos += 2; break; default: throw new PNGException("illegal type/depth"); } /*visit (row, col, min (bHeight, height - row), min (bWidth, width - col)); */ col += colInc; } if (interlaceMethod == 0) if (wPixels != null) { /* code changed. target not needed here t.setPixels(0,row,width,1,cm,wPixels,0,width); */ // code added to make it work with ImageDecoder arch sendPixels(0, row, width, 1, wPixels, 0, width); // end of adding } else { /* code changed. target not needed here t.setPixels(0,row,width,1,cm,bPixels,0,width); */ // code added to make it work with ImageDecoder arch sendPixels(0, row, width, 1, bPixels, 0, width); // end of adding } row += rowInc; rowOffset += rowInc * rowStride; byte[] T = rowByteBuffer; rowByteBuffer = prevRowByteBuffer; prevRowByteBuffer = T; firstRow = false; } if (interlaceMethod != 0) if (wPixels != null) { /* code changed. target not needed here t.setPixels(0,0,width,height,cm,wPixels,0,width); */ // code added to make it work with ImageDecoder arch sendPixels(0, 0, width, height, wPixels, 0, width); // end of adding } else { /* code changed. target not needed here t.setPixels(0,0,width,height,cm,bPixels,0,width); */ // code added to make it work with ImageDecoder arch sendPixels(0, 0, width, height, bPixels, 0, width); // end of adding } } /* Here, the function "visit(row,column,height,width)" obtains the next transmitted pixel and paints a rectangle of the specified height and width, whose upper-left corner is at the specified row and column, using the color indicated by the pixel. Note that row and column are measured from 0,0 at the upper left corner. */ /* code not needed, don't deal with target if((t=target)!=null) { if(properties!=null) t.setProperties(properties); t.imageComplete(ImageConsumer.STATICIMAGEDONE); */ imageComplete(ImageConsumer.STATICIMAGEDONE, true); /* code not needed } is.close(); */ } catch (IOException e) { if (!aborted) { /* code not needed if((t=target)!=null) { PNGEncoder.prChunk(e.toString(),inbuf,pos,limit-pos,true); */ property("error", e); /* code not needed t.setProperties(properties); t.imageComplete(ImageConsumer.IMAGEERROR|ImageConsumer.STATICIMAGEDONE); */ imageComplete(ImageConsumer.IMAGEERROR | ImageConsumer.STATICIMAGEDONE, true); throw e; } } finally { try { close(); } catch (Throwable e) { } /* code not needed target = null; endTurn(); */ } }
@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!"); } }
/** * 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); } } } } }
/** * Filters the information provided in the <code>setPixels</code> method of the <code> * ImageConsumer</code> interface which takes an array of integers. * * <p>Note: This method is intended to be called by the <code>ImageProducer</code> of the <code> * Image</code> whose pixels are being filtered. Developers using this class to retrieve pixels * from an image should avoid calling this method directly since that operation could result in * problems with retrieving the requested pixels. * * @throws IllegalArgumentException if width or height are less than zero. * @see ImageConsumer#setPixels(int, int, int, int, ColorModel, int[], int, int) */ public void setPixels( int x, int y, int w, int h, ColorModel model, int pixels[], int off, int scansize) { // Fix 4184230 if (w < 0 || h < 0) { throw new IllegalArgumentException("Width (" + w + ") and height (" + h + ") must be > 0"); } // Nothing to do if (w == 0 || h == 0) { return; } if (y < 0) { int diff = -y; if (diff >= h) { return; } off += scansize * diff; y += diff; h -= diff; } if (y + h > height) { h = height - y; if (h <= 0) { return; } } if (x < 0) { int diff = -x; if (diff >= w) { return; } off += diff; x += diff; w -= diff; } if (x + w > width) { w = width - x; if (w <= 0) { return; } } if (intPixels == null) { if (bytePixels == null) { intPixels = new int[width * height]; this.model = model; } else { convertToRGB(); } } int dstPtr = y * width + x; if (this.model == model) { for (int sh = h; sh > 0; sh--) { System.arraycopy(pixels, off, intPixels, dstPtr, w); off += scansize; dstPtr += width; } } else { if (this.model != ColorModel.getRGBdefault()) { convertToRGB(); } int dstRem = width - w; int srcRem = scansize - w; for (int sh = h; sh > 0; sh--) { for (int sw = w; sw > 0; sw--) { intPixels[dstPtr++] = model.getRGB(pixels[off++]); } off += srcRem; dstPtr += dstRem; } } }