Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java and Imaging. Paint paint() methodpaint() method AWT Coordinate SystemAWT Coordinate System Color & ColorModelColor & ColorModel –the java.awt.Color.

Similar presentations


Presentation on theme: "Java and Imaging. Paint paint() methodpaint() method AWT Coordinate SystemAWT Coordinate System Color & ColorModelColor & ColorModel –the java.awt.Color."— Presentation transcript:

1 Java and Imaging

2 Paint paint() methodpaint() method AWT Coordinate SystemAWT Coordinate System Color & ColorModelColor & ColorModel –the java.awt.Color class –the java.awt.image.ColorModel class

3 paint() method Java Peer Java Peer to draw, inherit Canvas, override paint to draw, inherit Canvas, override paint redraw screen WINDOW_ paint() EXPOSED update() Event repaint() clear component window

4 AWT Coordinate System

5 The java.awt.Color class Encapsulate RGB colorsEncapsulate RGB colors have static final Color object of frequent-used colorshave static final Color object of frequent-used colors public static final Color black; public Color(int red, int green, int blue); public Color brighter(); public Color darker(); public int getRed();

6 java.awt.image.ColorModel encapsulate the METHODS of TRANSLATION from PIXEL VALUESencapsulate the METHODS of TRANSLATION from PIXEL VALUES get alpha, red, green, blue value from pixelget alpha, red, green, blue value from pixel implemented by DirectColorModel, IndexColorModelimplemented by DirectColorModel, IndexColorModel public abstract class ColorModel; public colorModel(int nbits); public abstract getAlpha(int pixelvalue); public static ColorModel getRGBdefault(); // return default ColorModel 0xAARRGGBB

7 Drawing The Graphics classThe Graphics class Simple DrawingSimple Drawing Working With TextWorking With Text –Font –FontMetrics

8 java.awt.Graphics class contain current graphics context and methods for drawingcontain current graphics context and methods for drawing graphics context : fgcolor, bgcolor, font, etc.graphics context : fgcolor, bgcolor, font, etc. abstract class - actual java implementation and native library is provided by virtual machineabstract class - actual java implementation and native library is provided by virtual machine

9 Drawing Methods of Graphics

10 Simple Drawing import java.awt.*; import java.awt.event.*; public class DrawingCanvas extends Canvas implements MouseListener { Canvas implements MouseListener { protected Point pt; public DrawingCanvas() { pt = new Point(50, 50); pt = new Point(50, 50); addMouseListener(this); addMouseListener(this);} public Dimension getPreferredSize() { return new Dimension(100, 100); return new Dimension(100, 100);} public void mouseClicked(MouseEvent e) { pt = e.getPoint(); repaint(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void paint(Graphics g) { g.setColor(Color.blue); g.drawRect(pt.x, pt.y, 10, 10); }

11 java.awt.Font load Font object from font nameload Font object from font name public Font(String name, int style, int size); public static Font getFont(String nm);

12 java.awt.FontMetrics has methods to get information from Font objecthas methods to get information from Font object public FontMetrics(Font fn); public getAscent(); public getDescent();

13 Using images The Image classThe Image class Loading imagesLoading images –Loading –Keep Track of Image Loading With the MediaTracker classWith the MediaTracker class With the ImageObserver interface*With the ImageObserver interface* Displaying imagesDisplaying images

14 Using images - Manipulating images*Manipulating images* –imagefilter

15 java.awt.Image class encapsulate imageencapsulate image programmer can ’ t know about internal data structure representaing imageprogrammer can ’ t know about internal data structure representaing image public abstract Graphics getGraphics(); public abstract int getWidth(); public abstract int getHeight(); public Image createImage(ImageProducer); public Image createImage(int w, int h);

16 Loading automatic loading about JPEG and GIF imagesautomatic loading about JPEG and GIF images background loadingbackground loading use methods in java.applet.Applet or java.awt.Toolkituse methods in java.applet.Applet or java.awt.Toolkit load via filename or urlload via filename or url public abstract Image Toolkit.getImage(URL url); public abstract Image Toolkit.getImage(String file) Toolkit Component.getToolkit() or static Toolkit Toolkit.getDefaultToolkit()

17 java.awt.MediaTracker keep track of image loadingkeep track of image loading public MediaTracker(Component comp); public addImage(Image img, int id); public boolean checkAll(); public boolean checkID(int id); public boolean isErrorAny(); public void waitForAll();

18 java.awt.MediaTracker - MediaTracker tracker; MediaTracker tracker; tracker = new MediaTracker(this); Toolkit tk = Toolkit.getDefaultToolkit(); for (int i = 1; i <= 10; i++) { images[i-1] = tk.getImage("image" + i + ".gif"); tracker.addImage(images[i-1], i); } try { //Start downloading the images. Wait until they're loaded. tracker.waitForAll(); } catch (InterruptedException e) {} // in paint(); if (!tracker.checkAll()) { g.clearRect(0, 0, d.width, d.height); g.drawString("Please wait...", 0, d.height/2); } //If all images are loaded, draw. else {...//same code as before...

19 java.awt.image.ImageObserver interface loading loading imageUpdate() ImageObserver image width known height known loading

20 java.awt.image.ImageObserver public interface ImageObserver { public abstract boolean imageUpdate(image img, int infoflags, int x, int y, int width, int height); public abstract boolean imageUpdate(image img, int infoflags, int x, int y, int width, int height);} If image knows width and height, or loading pixels, call this methods with infoflags. if return true, no more call this methods Component implements ImageObserver if not completely loaded yet, repaint()

21 java.awt.image.ImageObserver public int Image.getWidth(ImageObserver observer)public int Image.getWidth(ImageObserver observer) –If the width is not known yet then the ImageObserver will be notified later and -1 will be returned. public boolean drawImage ( Image img, int x, int y, int width, int height, Color bgColor, ImageObserver observer )public boolean drawImage ( Image img, int x, int y, int width, int height, Color bgColor, ImageObserver observer ) –return immediately. return ture if image is fully initialized.if not, return false, and let img notify observer

22 Displaying images public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer);public abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer);public abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer); public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer);public abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer);

23 ImageFilter - startProduction() setPixels() ImageProducer ImageConsumer

24 ImageFilter - ImageConsumer ImageConsumer ImageFilter filter = new RotateFilter(angle); ImageProducer producer = new FilteredImageSource(souceImage.getSource(), filter); Image resultImage = createImage(producer); ImageProducer ImageFilter

25 Improving Animation Eliminating FlashingEliminating Flashing –Overrideing update() method –Clipping –Double Buffering –Speed up Image Loading with Clipping

26 Overriding update() method default update()default update() – clear all component's Background and call paint() –Component ’ s member method public void update(Graphics g) { DoActualDrawing(); DoActualDrawing();} public void paint(Graphics g) { update(g); update(g);}

27 Clipping public abstract void clipRect(int x, int y, int width, int height); public abstract void clipRect(int x, int y, int width, int height); –Clipping the Drawing Area public void update(Graphics g) { Graphics g2 = g.create(x, y, w, h); Graphics g2 = g.create(x, y, w, h); paint(g2); paint(g2);}

28 Double Buffering update drawing area one timeupdate drawing area one time Dimension offDimension; Image offImage; Graphics offGraphics; public void update(Graphics g) { if( (offGraphics == null) || ( d.width != offDimension.width) || (d.height != offDimension.height) ) { (d.height != offDimension.height) ) { offDimension = d; offDimension = d; offImage = createImage(d.width, d.height); offImage = createImage(d.width, d.height); offGraphics = offImage.getGraphics(); offGraphics = offImage.getGraphics(); } DoActualDrawing(offGraphics); DoActualDrawing(offGraphics); drawImage(offGraphics, 0, 0, this); drawImage(offGraphics, 0, 0, this);}

29 Speed up Image Loading with Clipping when loading images using URLs, most of the time is taken up by initiating HTTP connections.when loading images using URLs, most of the time is taken up by initiating HTTP connections. –make an image strip int stripWidth = imageStrip.getWidth(this); int stripHeight = imageStrip.getHeight(this); int imageWidth = stripWidth / numImages; g.clipRect(0, 0, imageWidth, stripHeight); g.drawImage(imageStrip, -imageNumber*imageWidth, 0, this);

30 New Features of Java1.1 Enhancement on Graphics ClipEnhancement on Graphics Clip Cropping, Scaling, and FlippingCropping, Scaling, and Flipping MemoryImageSourceMemoryImageSource PixelGrabberPixelGrabber

31 Enhancement on Clipping New methods of GraphicsNew methods of Graphics Shape getClip(); void setClip(Shape clip); void setClip(int x, int y, int w, int h); void getClipBounds();

32 Enhancement on Clipping Graphics g2 = g.create(); g2.clipRect(10, 10, 100, 100); g2.drawImage(img2, 10, 10, this); g2.dispose(); Shape oldclip = g.getClip(); g.clipRect(10, 10, 100, 100); g.drawImage(img2, 10, 10, this); g.setClip(oldclip);

33 Java Media APIs Java2DJava2D Java Advanced Imaging (JAI)Java Advanced Imaging (JAI) Java Media Framework (JMF)Java Media Framework (JMF) Java3DJava3D

34 java.awt.image Image is an abstract classImage is an abstract class Image objects are constructed in a platform specific mannerImage objects are constructed in a platform specific manner Two types of image objects:Two types of image objects: –Images created from an image source –Images created by an AWT component Component.createImage()Component.createImage()

35 Processing Images in AWT MemoryImageSource ImageProducer PixelGrabber MemoryImageSource

36 JAI models The producer/consumer modelThe producer/consumer model – 基本的 AWT 影像 model The immediate mode modelThe immediate mode model – 進階的 AWT 影像 model The pipeline modelThe pipeline model –The JAI 所使用的影像 model Push model Pull model AWT Push model Java 2D Immediate mode Pull Mode Image ImageProducer ImageConsumer ImageObserver BufferedImage Raster BufferedImageOp RasterOp RenderableImage RenderableImageOp RenderedOp RenderableOp TiledImage

37 BufferedImage Color Model Raster ColorSpaceSampleModel DataBuffer java.awt.image.BufferedImage Encapsulates the methods for translating a pixel value to color components (ex. red/green/blue) and an alpha component for rendering

38 DataBuffer java.awt.image.DataBufferjava.awt.image.DataBuffer DataBuffer stores pixel data as one or more arrays of primitive data types.DataBuffer stores pixel data as one or more arrays of primitive data types. Java2D buffer types:Java2D buffer types: –Byte –Integer –Short –Unsigned short JAI buffer types:JAI buffer types: –Double –Float

39 Sample Model SampleMode describes how pixels are stored in the DataBuffer.SampleMode describes how pixels are stored in the DataBuffer. –Packed Models Single-pixel packed modelSingle-pixel packed model Multiple-pixel packed sample modelMultiple-pixel packed sample model –Component Models Component sample modelComponent sample model

40 ColorModel Converts raster pixel samples into color components for displayingConverts raster pixel samples into color components for displaying –Pixel samples are packed into a short integer (16 bits). Each sample would be 5 bits. –If displayed on a color monitor (0-255) per channel, the resulting image would appear dark. –Color model handles the conversion.

41 ColorSpaces Device independent/dependentDevice independent/dependent Converts between devicesConverts between devices Supports many color spaces including:Supports many color spaces including: –CMYK –HSV (HSB) –CIEXYZ –sRGB –ICC Color Profile Create ColorSpace via factoryCreate ColorSpace via factory

42 Code Example Creating an Image

43 Alpha Channel A mixing factor to control the linear interpolation of foreground and background colors.A mixing factor to control the linear interpolation of foreground and background colors. Varies from 0 to 1Varies from 0 to 1 –0 indicates no coverage (clear) –1 indicates full coverage Each sample is multiplied by the alpha channelEach sample is multiplied by the alpha channel

44 Transformations Definitions:Definitions: –Transformation is a function that maps an object from one point to another. –Affine transform preserves: FinitenessFiniteness ParallelismParallelism Transformations:Transformations: TranslationTranslation ScalingScaling RotationRotation ReflectionReflection ShearShear

45 Translation y x

46 Scaling y x

47 Rotation y x

48 Reflection y x

49 Shear y x

50 Transformations Transformations can be concatenated:Transformations can be concatenated: –C = Translate * Scale * Rotate * Shear Java Classes:Java Classes: –AffineTransform ( java.awt.geom ) –AffineTransformOp ( java.awt.image )

51 Interpolation What is Interpolation?What is Interpolation? –Interpolation is a process of generating a value of a pixel based on its neighbors. Types of Interpolation:Types of Interpolation: –Nearest-neighbor –Linear –Bilinear –Trilinear –Cubic

52 Interpolation - Linear P (x+1) pxpx P x’ pxpx P (x+1) d xx’x+1 Interpolated Pixel Building Imaging Applications with Java p272

53 Bilinear Interpolation dydy dxdx P (x,y) P (x+1,y) P (x,y+1) P (x+1,y+1) P (x’,y’)

54 Trilinear Interpolation dydy dxdx dzdz P (x’,y’,z’) P (x,y,z) P (x,y+1,z) P (x,y,z+1)

55 Cubic Interpolation x x+1x’x+2x+3 pxpx p x+1 p x’ p x+2 p x+3 Pixel location Pixel value pxpx p x+1 p x’ p x+2 p x+3 p x = ax 3 + bx 2 + cx + d

56 Convolution Kernels Image I(i,j) Convolution kernel is a matrix f(m,n) Example: f(m,n) =

57 Convolution Kernel Example 15687 851768 910111112 231578 910432 I(3,3) = (1*5) + (1*17) + (1*6) + (2*11) + (1*11) + (1*1) + (1*5) + (1*7) = 74 f(m,n)=

58 Smoothing Filters Weighted average of the neighboring pixels. Often approximate a Gaussian function.

59 Edge Detectors Laplacian

60 Sharpening

61 Java2D Image Operations AffineTransformOpAffineTransformOp ConvolveOpConvolveOp LookupOpLookupOp RescaleOpRescaleOp ColorConvertOpColorConvertOp BandCombineOp (RasterOp)BandCombineOp (RasterOp)

62 Code Example Interpolation/Edge Detection

63 Image I/O “ The Java Image I/O API provides a pluggable architecture for working with images stored in files and accessed across the network. It offers substantially more flexibility and power than the previously available APIs for loading and saving images. ”

64 Image I/O Key Features Read & write multiple image formatsRead & write multiple image formats –JPG, PNG, GIF, etc. Expose image metadata uniformlyExpose image metadata uniformly –W3C DOM Provide Access to thumbnail imagesProvide Access to thumbnail images Support multi-image filesSupport multi-image files Provide pluggable architecture for additional formatsProvide pluggable architecture for additional formats Handle large image filesHandle large image files

65 Image I/O Packages javax.imageiojavax.imageio –ImageIO, ImageReader, ImageWriter javax.imageio.eventjavax.imageio.event javax.imageio.metadatajavax.imageio.metadata –IIOMetadata, IIOMetadataFormatImpl, IIOMetadataNode javax.imageio.spijavax.imageio.spi Javax.imageio.streamJavax.imageio.stream

66 Custom Plug-ins Implement:Implement: –Reader - extends ImageReader –Writer - extends ImageWriter –Provider interfaces: ImageReaderSpiImageReaderSpi ImageWriterSpiImageWriterSpi Optionally provideOptionally provide –Image and stream metadata classes extending IIOMetadata

67 Image I/O Code Examples Reading & writing imagesReading & writing images Querying for supported image typesQuerying for supported image types Implementing a plug-inImplementing a plug-in

68 Java Advanced Image

69 JAI Concepts Multi-tiled imagesMulti-tiled images Deferred executionDeferred execution Network imagesNetwork images Image property managementImage property management Image operators with multiple sourcesImage operators with multiple sources Three-dimensional image dataThree-dimensional image data

70 Image Processing DAGs constantfileload add Display Widgets rotate

71 JAI Operator Categories Point OperatorsPoint Operators Area OperatorsArea Operators Geometric OperatorsGeometric Operators Color Quantization OperatorsColor Quantization Operators File OperatorsFile Operators Frequency OperatorsFrequency Operators Statistical OperatorsStatistical Operators Edge Extraction OperatorsEdge Extraction Operators Miscellaneous OperatorsMiscellaneous Operators

72 Point Operators AbsoluteAddAddCollectionAddConstAddConstToCollection AndAndConstBandCombineBandSelectClamp ColorConvertCompositeConstantDivideDivideByConst DivideComplexDivideIntoConstExpInvertLog LookupMatchCDFMaxMinMultiply MultiplyConstMultiplyComplexMultiplyConstNotOr OrConstOverlayPatternPiecewiseRescale SubtractSubtractConstSubtractConstSubtractFromConstThreshold XorXorConst

73 Area Operators BorderBorder BoxFilterBoxFilter ConvolveConvolve CropCrop MedianFilterMedianFilter

74 Geometric Operators AffineAffine RotateRotate ScaleScale ShearShear TranslateTranslate TransposeTranspose WarpWarp

75 Color Quantization ErrorDiffusionErrorDiffusion OrderedDitherOrderedDither

76 File Operators AWTImageBMP EncodeFileLoad FilestoreFormat FPXGIF IIPIIPResolution JPEGPNG NMStream TIFFURL

77 Frequency Operators ConjugateDCT DFTIDCT IDFTImageFunction MagnitudeMagnitudeSquared PeriodicShiftPhase PolarToComplex

78 API

79 ParameterBlock 用來儲存 RenderableImageOp 或處理影像專 用 class 所需要的 sources 與 參數資訊 用來儲存 RenderableImageOp 或處理影像專 用 class 所需要的 sources 與 參數資訊 雖然你可以放置任意的 objcet 到他的 source vector, 但是一般都只是放置 RenderedImages 與 RenderableImage object. 雖然你可以放置任意的 objcet 到他的 source vector, 但是一般都只是放置 RenderedImages 與 RenderableImage object. 所有放在 ParameterBlock 中的參數都以 object 方式表示 所有放在 ParameterBlock 中的參數都以 object 方式表示 short s; add(s); short s; add(s); short s; add( new Short(s)); short s; add( new Short(s)); 意思是一樣的

80 ParameterBlock Side Effect ParameterBlock 中的 get 與 set methods 都是 使用 referenceParameterBlock 中的 get 與 set methods 都是 使用 reference ParameterBlock addSource(ParameterBlock pb, RenderableImage im) { ParameterBlock pb1 = new ParameterBlock(pb.getSources()); pb1.addSource(im); return pb1; } ParameterBlock addSource(ParameterBlock pb, RenderableImage im) { ParameterBlock pb1 = new ParameterBlock(pb.getSources()); pb1.addSource(im); return pb1; } 例如 : pb1 與 pb share 相同的 source Vector (a change in either is visible to both) pb1 與 pb share 相同的 source Vector (a change in either is visible to both) ParameterBlock pb1 = new ParameterBlock( pb.getSources().clone() );

81 ParameterBlock clone method shadowClone method clone method 提供 ParameterBlock 中的 source 與 參數 Vectors 的內容複製clone method 提供 ParameterBlock 中的 source 與 參數 Vectors 的內容複製 所以你可以藉此更改 Sources 的順序, 當改變內容時, 會有 Side Effect 所以你可以藉此更改 Sources 的順序, 當改變內容時, 會有 Side Effect shadowClone 複製 vectors 本身的 referenceshadowClone 複製 vectors 本身的 reference 即只有 references 的複製 Source Vector Parameter Vector Source Vector Parameter Vector Objects Source Vector Parameter Vector Source Vector Parameter Vector Objects

82 ParameterBlock add method 傳回的是 thisadd method 傳回的是 this 所以我們可以方便增加 objects 所以我們可以方便增加 objects ParameterBlock pb = new ParameterBlock(); op = new RenderableImageOp("operation", pb.add(arg1).add(arg2) ); ParameterBlock pb = new ParameterBlock(); op = new RenderableImageOp("operation", pb.add(arg1).add(arg2) ); 連續增加新的 objects

83 More api import java.awt.Frame; import java.awt.image.renderable.ParameterBlock; import java.io.IOException; import javax.media.jai.Interpolation; // bilinear operator usage import javax.media.jai.JAI; import javax.media.jai.RenderedOp; // operator import com.sun.media.jai.codec.FileSeekableStream; // 影像解碼使用 import javax.media.jai.widget.ScrollingImagePanel; 這個程式可以 decode 所有 JAI 支援的圖形檔案格式 (GIF,JPEG,TIFF,BMP,PNM,PNG) 到 RenderedImage. 並且將影像利用 bilinear interpolation 的方式放大 2 倍

84 EX1 public class JAISampleProgram { public static void main(String[] args) { // Step 1: FileSeekableStream stream = null; try { stream = new FileSeekableStream("as01.jpg"); } catch (IOException e) { e.printStackTrace(); System.exit(0); } // Step 2: RenderedOp image1 = JAI.create("stream", stream); public class JAISampleProgram { public static void main(String[] args) { // Step 1: FileSeekableStream stream = null; try { stream = new FileSeekableStream("as01.jpg"); } catch (IOException e) { e.printStackTrace(); System.exit(0); } // Step 2: RenderedOp image1 = JAI.create("stream", stream); 利用 FileSeekableStream 建立影像檔案 串流 利用 FileSeekableStream 建立影像檔案 串流

85 scale operator // Step 3: Interpolation interp = Interpolation.getInstance( Interpolation.INTERP_BILINEAR); // Step 4: ParameterBlock params = new ParameterBlock(); params.addSource(image1); params.add(2.0F); // x scale factor params.add(2.0F); // y scale factor params.add(0.0F); // x translate params.add(0.0F); // y translate params.add(interp); // interpolation method // Step 5: 建立一個 operator 來 scale 影像 RenderedOp image2 = JAI.create("scale", params); // Step 3: Interpolation interp = Interpolation.getInstance( Interpolation.INTERP_BILINEAR); // Step 4: ParameterBlock params = new ParameterBlock(); params.addSource(image1); params.add(2.0F); // x scale factor params.add(2.0F); // y scale factor params.add(0.0F); // x translate params.add(0.0F); // y translate params.add(interp); // interpolation method // Step 5: 建立一個 operator 來 scale 影像 RenderedOp image2 = JAI.create("scale", params); Interpolation 物件使用 bilinear 演算法作 scale Interpolation 物件使用 bilinear 演算法作 scale 執行 scale operator 指定 scale 處理目標物

86 API // Scale int width = image2.getWidth(); int height = image2.getHeight(); // attach scrolling panel ScrollingImagePanel panel = new ScrollingImagePanel( image2, width, height); /* Create a frame to contain the panel. */ Frame window = new Frame("JAI Sample Program"); window.add(panel); window.pack(); window.show(); } // Scale int width = image2.getWidth(); int height = image2.getHeight(); // attach scrolling panel ScrollingImagePanel panel = new ScrollingImagePanel( image2, width, height); /* Create a frame to contain the panel. */ Frame window = new Frame("JAI Sample Program"); window.add(panel); window.pack(); window.show(); } 利用 ScallingImagePanel 秀結果 JAISampleProgram.jpx

87 Rendered Graphics the simplest form of rendering in JAIthe simplest form of rendering in JAI Rendered graphs are useful when it is necessary to work directly with the pixelsRendered graphs are useful when it is necessary to work directly with the pixels ImmediateImmediate –the image source: have been evaluated at the moment it is instantiated and added to the graph have been evaluated at the moment it is instantiated and added to the graph –a new operation is added to the chain: compute its results immediately.compute its results immediately.

88 Rendered Graphics A Rendered graphA Rendered graph –nodes are usually instances of the RenderedOp (any subclass of PlanarImage ) Image sourcesImage sources –objects that implement the RenderedImage interface

89 import javax.jai.*; import javax.jai.widget.*; import java.awt.Frame; public class AddExample extends Frame { ScrollingImagePanel imagePanel1; public AddExample(ParameterBlock param1, ParameterBlock param2) { RenderedOp im0 = JAI.create("constant", param1);. RenderedOp im1 = JAI.create("constant", param2); RenderedOp im2 = JAI.create("add", im0, im1); // Display the original in a scrolling window imagePanel1 = new ScrollingImagePanel(im2, 100, 100); // Add the display widget to our frame. add(imagePanel1); } Create a constant image Create another constant image Add the two images together. Example

90 Renderable Graphs A Renderable graphA Renderable graph –is made up of nodes implementing the RenderableImage interface Instance of RenderableOP

91 Example reads a TIFF file, inverts its pixel values, then adds a constant value to the pixelsreads a TIFF file, inverts its pixel values, then adds a constant value to the pixels

92 RenderedOp sourceImg = JAI.create("TIFF", ” Jing01.tiff ” ); ParameterBlock pb = new ParameterBlock(); pb.addSource(sourceImg); pb.add(null).add(null).add(null).add(null).add(null); RenderableImage ren = JAI.createRenderable("renderable", pb); ParameterBlock pb1 = new ParameterBlock(); pb1.addSource(ren); RenderableOp Op1 = JAI.createRenderable("invert", pb1); ParameterBlock pb2 = new ParameterBlock(); pb2.addSource(Op1); // Op1 as the source pb2.add(2.0f); // 2.0f as the constant RenderableOp Op2 = JAI.createRenderable("addconst", pb2); AffineTransform screenResolution =...; RenderContext rc = new RenderContext(screenResolution); RenderedImage rndImg1 = Op2.createRendering(rc); // Display the rendering onscreen using screenResolution. imagePanel1 = new ScrollingImagePanel(rndImg1, 100, 100); 將 Rendered Image 轉換成 RenderableImage 建立反相 operator 建立 addconst operator Get a rendering

93 // 取出 Scale 後的影像寬高 int width = image2.getWidth(); int height = image2.getHeight(); // Create the rotation angle (45 degrees) and convert to // radians. int value = 45; float angle = (float) (value * (Math.PI / 180.0F)); // Create a ParameterBlock and specify the source and // parameters ParameterBlock pb = new ParameterBlock(); pb.addSource(image2); // The source image pb.add(0.0F); // The x origin pb.add(0.0F); // The y origin pb.add(angle); // The rotation angle pb.add(interp); // The interpolation // Create the rotate operation RenderedOp RotatedImage = JAI.create("Rotate", pb, null); Geometric Transformation Rotation 指定 rotate 處理目標物 Rotation


Download ppt "Java and Imaging. Paint paint() methodpaint() method AWT Coordinate SystemAWT Coordinate System Color & ColorModelColor & ColorModel –the java.awt.Color."

Similar presentations


Ads by Google