Java Tutorial/SWT/SWT Image — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:21, 31 мая 2010
Содержание
- 1 17. Convert between SWT Image and AWT BufferedImage
- 2 17. Converts a buffered image to SWT ImageData.
- 3 17. Converts an AWT image to SWT.
- 4 17. Create an exact copy of the image
- 5 17. Create an image that has a disabled look
- 6 17. Create an image that has the grayscale look
- 7 17. Create ImageData from PaletteData
- 8 17. Create Image from byte array
- 9 17. Creating an Empty Image
- 10 17. Creating an Image From a File
- 11 17. Creating an Image From an ImageData
- 12 17. Creating an Image From Another Image
- 13 17. Creating Images
- 14 17. Disposal Method Constants
- 15 17. Drawing Images
- 16 17. Draw part of an Image
- 17 17. GC example snippet: create an icon (in memory)
- 18 17. Get an ImageData instance from an existing Image
- 19 17. Get ImageData from Image
- 20 17. Images created using different flags for Label
- 21 17. Load image from file: an input stream and Class.getResourceAsStream()
- 22 17. Load image from file: Create an input stream and pass the input stream to the constructor:
- 23 17. Paint on an Image
- 24 17. Rotate Image
- 25 17. SWT can display graphic images from files
- 26 17. Type Constants
- 27 17. Use ImageData to create a new image
- 28 17. Using code to Create Image
17. Convert between SWT Image and AWT BufferedImage
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
//package org.eclipse.swt.snippets;
/*
* example snippet: convert between SWT Image and AWT BufferedImage
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
public class AWTBufferedImageSWTImage {
static BufferedImage convertToAWT(ImageData data) {
ColorModel colorModel = null;
PaletteData palette = data.palette;
if (palette.isDirect) {
colorModel = new DirectColorModel(data.depth, palette.redMask, palette.greenMask,
palette.blueMask);
BufferedImage bufferedImage = new BufferedImage(colorModel, colorModel
.createCompatibleWritableRaster(data.width, data.height), false, null);
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[3];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
int pixel = data.getPixel(x, y);
RGB rgb = palette.getRGB(pixel);
pixelArray[0] = rgb.red;
pixelArray[1] = rgb.green;
pixelArray[2] = rgb.blue;
raster.setPixels(x, y, 1, 1, pixelArray);
}
}
return bufferedImage;
} else {
RGB[] rgbs = palette.getRGBs();
byte[] red = new byte[rgbs.length];
byte[] green = new byte[rgbs.length];
byte[] blue = new byte[rgbs.length];
for (int i = 0; i < rgbs.length; i++) {
RGB rgb = rgbs[i];
red[i] = (byte) rgb.red;
green[i] = (byte) rgb.green;
blue[i] = (byte) rgb.blue;
}
if (data.transparentPixel != -1) {
colorModel = new IndexColorModel(data.depth, rgbs.length, red, green, blue,
data.transparentPixel);
} else {
colorModel = new IndexColorModel(data.depth, rgbs.length, red, green, blue);
}
BufferedImage bufferedImage = new BufferedImage(colorModel, colorModel
.createCompatibleWritableRaster(data.width, data.height), false, null);
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[1];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
int pixel = data.getPixel(x, y);
pixelArray[0] = pixel;
raster.setPixel(x, y, pixelArray);
}
}
return bufferedImage;
}
}
static ImageData convertToSWT(BufferedImage bufferedImage) {
if (bufferedImage.getColorModel() instanceof DirectColorModel) {
DirectColorModel colorModel = (DirectColorModel) bufferedImage.getColorModel();
PaletteData palette = new PaletteData(colorModel.getRedMask(), colorModel.getGreenMask(),
colorModel.getBlueMask());
ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(),
colorModel.getPixelSize(), palette);
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[3];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
raster.getPixel(x, y, pixelArray);
int pixel = palette.getPixel(new RGB(pixelArray[0], pixelArray[1], pixelArray[2]));
data.setPixel(x, y, pixel);
}
}
return data;
} else if (bufferedImage.getColorModel() instanceof IndexColorModel) {
IndexColorModel colorModel = (IndexColorModel) bufferedImage.getColorModel();
int size = colorModel.getMapSize();
byte[] reds = new byte[size];
byte[] greens = new byte[size];
byte[] blues = new byte[size];
colorModel.getReds(reds);
colorModel.getGreens(greens);
colorModel.getBlues(blues);
RGB[] rgbs = new RGB[size];
for (int i = 0; i < rgbs.length; i++) {
rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF, blues[i] & 0xFF);
}
PaletteData palette = new PaletteData(rgbs);
ImageData data = new ImageData(bufferedImage.getWidth(), bufferedImage.getHeight(),
colorModel.getPixelSize(), palette);
data.transparentPixel = colorModel.getTransparentPixel();
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[1];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
raster.getPixel(x, y, pixelArray);
data.setPixel(x, y, pixelArray[0]);
}
}
return data;
}
return null;
}
static ImageData createSampleImage(Display display) {
Image image = new Image(display, 100, 100);
Rectangle bounds = image.getBounds();
GC gc = new GC(image);
gc.setBackground(display.getSystemColor(SWT.COLOR_BLUE));
gc.fillRectangle(bounds);
gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN));
gc.fillOval(0, 0, bounds.width, bounds.height);
gc.setForeground(display.getSystemColor(SWT.COLOR_RED));
gc.drawLine(0, 0, bounds.width, bounds.height);
gc.drawLine(bounds.width, 0, 0, bounds.height);
gc.dispose();
ImageData data = image.getImageData();
image.dispose();
return data;
}
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("SWT Image");
ImageData data;
if (args.length > 0) {
String fileName = args[0];
data = new ImageData(fileName);
} else {
data = createSampleImage(display);
}
final Image swtImage = new Image(display, data);
final BufferedImage awtImage = convertToAWT(data);
final Image swtImage2 = new Image(display, convertToSWT(awtImage));
shell.addListener(SWT.Paint, new Listener() {
public void handleEvent(Event e) {
int y = 10;
if (swtImage != null) {
e.gc.drawImage(swtImage, 10, y);
y += swtImage.getBounds().height + 10;
}
if (swtImage2 != null) {
e.gc.drawImage(swtImage2, 10, y);
}
}
});
Frame frame = new Frame() {
public void paint(Graphics g) {
Insets insets = getInsets();
if (awtImage != null) {
g.drawImage(awtImage, 10 + insets.left, 10 + insets.top, null);
}
}
};
frame.setTitle("AWT Image");
shell.setLocation(50, 50);
Rectangle bounds = swtImage.getBounds();
shell.setSize(bounds.width + 50, bounds.height * 2 + 100);
Point size = shell.getSize();
Point location = shell.getLocation();
Insets insets = frame.getInsets();
frame.setLocation(location.x + size.x + 10, location.y);
frame.setSize(size.x - (insets.left + insets.right), size.y - (insets.top + insets.bottom));
frame.setVisible(true);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
if (swtImage != null)
swtImage.dispose();
if (swtImage2 != null)
swtImage.dispose();
frame.dispose();
display.dispose();
/*
* Note: If you are using JDK 1.3.x, you need to use System.exit(0) at the
* end of your program to exit AWT. This is because in 1.3.x, AWT does not
* exit when the frame is disposed, because the AWT thread is not a daemon.
* This was fixed in JDK 1.4.x with the addition of the AWT Shutdown thread.
*/
}
}
17. Converts a buffered image to SWT ImageData.
/*
* JFreeChart : a free chart library for the Java(tm) platform
*
*
* (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -------------
* SWTUtils.java
* -------------
* (C) Copyright 2006, 2007, by Henry Proudhon and Contributors.
*
* Original Author: Henry Proudhon (henry.proudhon AT ensmp.fr);
* Contributor(s): Rainer Blessing;
* David Gilbert (david.gilbert@object-refinery.ru);
* Christoph Beck.
*
* Changes
* -------
* 01-Aug-2006 : New class (HP);
* 16-Jan-2007 : Use FontData.getHeight() instead of direct field access (RB);
* 31-Jan-2007 : Moved the dummy JPanel from SWTGraphics2D.java,
* added a new convert method for mouse events (HP);
* 12-Jul-2007 : Improved the mouse event conversion with buttons
* and modifiers handling, patch sent by Christoph Beck (HP);
* 27-Aug-2007 : Modified toAwtMouseEvent signature (HP);
* 27-Nov-2007 : Moved convertToSWT() method from SWTGraphics2D and added
* convertAWTImageToSWT() (DG);
* 01-Jul-2008 : Simplify AWT/SWT font style conversions (HP);
*
*/
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import javax.swing.JPanel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
/**
* Utility class gathering some useful and general method.
* Mainly convert forth and back graphical stuff between
* awt and swt.
*/
public class SWTUtils {
private final static String Az = "ABCpqr";
/** A dummy JPanel used to provide font metrics. */
protected static final JPanel DUMMY_PANEL = new JPanel();
/**
* Creates an AWT <code>MouseEvent</code> from a swt event.
* This method helps passing SWT mouse event to awt components.
* @param event The swt event.
* @return A AWT mouse event based on the given SWT event.
*/
public static MouseEvent toAwtMouseEvent(org.eclipse.swt.events.MouseEvent event) {
int button = MouseEvent.NOBUTTON;
switch (event.button) {
case 1: button = MouseEvent.BUTTON1; break;
case 2: button = MouseEvent.BUTTON2; break;
case 3: button = MouseEvent.BUTTON3; break;
}
int modifiers = 0;
if ((event.stateMask & SWT.CTRL) != 0) {
modifiers |= InputEvent.CTRL_DOWN_MASK;
}
if ((event.stateMask & SWT.SHIFT) != 0) {
modifiers |= InputEvent.SHIFT_DOWN_MASK;
}
if ((event.stateMask & SWT.ALT) != 0) {
modifiers |= InputEvent.ALT_DOWN_MASK;
}
MouseEvent awtMouseEvent = new MouseEvent(DUMMY_PANEL, event.hashCode(),
event.time, modifiers, event.x, event.y, 1, false, button);
return awtMouseEvent;
}
/**
* Converts an AWT image to SWT.
*
* @param image the image (<code>null</code> not permitted).
*
* @return Image data.
*/
public static ImageData convertAWTImageToSWT(Image image) {
if (image == null) {
throw new IllegalArgumentException("Null "image" argument.");
}
int w = image.getWidth(null);
int h = image.getHeight(null);
if (w == -1 || h == -1) {
return null;
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return convertToSWT(bi);
}
/**
* Converts a buffered image to SWT <code>ImageData</code>.
*
* @param bufferedImage the buffered image (<code>null</code> not
* permitted).
*
* @return The image data.
*/
public static ImageData convertToSWT(BufferedImage bufferedImage) {
if (bufferedImage.getColorModel() instanceof DirectColorModel) {
DirectColorModel colorModel
= (DirectColorModel) bufferedImage.getColorModel();
PaletteData palette = new PaletteData(colorModel.getRedMask(),
colorModel.getGreenMask(), colorModel.getBlueMask());
ImageData data = new ImageData(bufferedImage.getWidth(),
bufferedImage.getHeight(), colorModel.getPixelSize(),
palette);
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[3];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
raster.getPixel(x, y, pixelArray);
int pixel = palette.getPixel(new RGB(pixelArray[0],
pixelArray[1], pixelArray[2]));
data.setPixel(x, y, pixel);
}
}
return data;
}
else if (bufferedImage.getColorModel() instanceof IndexColorModel) {
IndexColorModel colorModel = (IndexColorModel)
bufferedImage.getColorModel();
int size = colorModel.getMapSize();
byte[] reds = new byte[size];
byte[] greens = new byte[size];
byte[] blues = new byte[size];
colorModel.getReds(reds);
colorModel.getGreens(greens);
colorModel.getBlues(blues);
RGB[] rgbs = new RGB[size];
for (int i = 0; i < rgbs.length; i++) {
rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF,
blues[i] & 0xFF);
}
PaletteData palette = new PaletteData(rgbs);
ImageData data = new ImageData(bufferedImage.getWidth(),
bufferedImage.getHeight(), colorModel.getPixelSize(),
palette);
data.transparentPixel = colorModel.getTransparentPixel();
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[1];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
raster.getPixel(x, y, pixelArray);
data.setPixel(x, y, pixelArray[0]);
}
}
return data;
}
return null;
}
}
17. Converts an AWT image to SWT.
/*
* JFreeChart : a free chart library for the Java(tm) platform
*
*
* (C) Copyright 2000-2007, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* -------------
* SWTUtils.java
* -------------
* (C) Copyright 2006, 2007, by Henry Proudhon and Contributors.
*
* Original Author: Henry Proudhon (henry.proudhon AT ensmp.fr);
* Contributor(s): Rainer Blessing;
* David Gilbert (david.gilbert@object-refinery.ru);
* Christoph Beck.
*
* Changes
* -------
* 01-Aug-2006 : New class (HP);
* 16-Jan-2007 : Use FontData.getHeight() instead of direct field access (RB);
* 31-Jan-2007 : Moved the dummy JPanel from SWTGraphics2D.java,
* added a new convert method for mouse events (HP);
* 12-Jul-2007 : Improved the mouse event conversion with buttons
* and modifiers handling, patch sent by Christoph Beck (HP);
* 27-Aug-2007 : Modified toAwtMouseEvent signature (HP);
* 27-Nov-2007 : Moved convertToSWT() method from SWTGraphics2D and added
* convertAWTImageToSWT() (DG);
* 01-Jul-2008 : Simplify AWT/SWT font style conversions (HP);
*
*/
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DirectColorModel;
import java.awt.image.IndexColorModel;
import java.awt.image.WritableRaster;
import javax.swing.JPanel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Device;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
/**
* Utility class gathering some useful and general method.
* Mainly convert forth and back graphical stuff between
* awt and swt.
*/
public class SWTUtils {
private final static String Az = "ABCpqr";
/** A dummy JPanel used to provide font metrics. */
protected static final JPanel DUMMY_PANEL = new JPanel();
/**
* Creates an AWT <code>MouseEvent</code> from a swt event.
* This method helps passing SWT mouse event to awt components.
* @param event The swt event.
* @return A AWT mouse event based on the given SWT event.
*/
public static MouseEvent toAwtMouseEvent(org.eclipse.swt.events.MouseEvent event) {
int button = MouseEvent.NOBUTTON;
switch (event.button) {
case 1: button = MouseEvent.BUTTON1; break;
case 2: button = MouseEvent.BUTTON2; break;
case 3: button = MouseEvent.BUTTON3; break;
}
int modifiers = 0;
if ((event.stateMask & SWT.CTRL) != 0) {
modifiers |= InputEvent.CTRL_DOWN_MASK;
}
if ((event.stateMask & SWT.SHIFT) != 0) {
modifiers |= InputEvent.SHIFT_DOWN_MASK;
}
if ((event.stateMask & SWT.ALT) != 0) {
modifiers |= InputEvent.ALT_DOWN_MASK;
}
MouseEvent awtMouseEvent = new MouseEvent(DUMMY_PANEL, event.hashCode(),
event.time, modifiers, event.x, event.y, 1, false, button);
return awtMouseEvent;
}
/**
* Converts an AWT image to SWT.
*
* @param image the image (<code>null</code> not permitted).
*
* @return Image data.
*/
public static ImageData convertAWTImageToSWT(Image image) {
if (image == null) {
throw new IllegalArgumentException("Null "image" argument.");
}
int w = image.getWidth(null);
int h = image.getHeight(null);
if (w == -1 || h == -1) {
return null;
}
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return convertToSWT(bi);
}
/**
* Converts a buffered image to SWT <code>ImageData</code>.
*
* @param bufferedImage the buffered image (<code>null</code> not
* permitted).
*
* @return The image data.
*/
public static ImageData convertToSWT(BufferedImage bufferedImage) {
if (bufferedImage.getColorModel() instanceof DirectColorModel) {
DirectColorModel colorModel
= (DirectColorModel) bufferedImage.getColorModel();
PaletteData palette = new PaletteData(colorModel.getRedMask(),
colorModel.getGreenMask(), colorModel.getBlueMask());
ImageData data = new ImageData(bufferedImage.getWidth(),
bufferedImage.getHeight(), colorModel.getPixelSize(),
palette);
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[3];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
raster.getPixel(x, y, pixelArray);
int pixel = palette.getPixel(new RGB(pixelArray[0],
pixelArray[1], pixelArray[2]));
data.setPixel(x, y, pixel);
}
}
return data;
}
else if (bufferedImage.getColorModel() instanceof IndexColorModel) {
IndexColorModel colorModel = (IndexColorModel)
bufferedImage.getColorModel();
int size = colorModel.getMapSize();
byte[] reds = new byte[size];
byte[] greens = new byte[size];
byte[] blues = new byte[size];
colorModel.getReds(reds);
colorModel.getGreens(greens);
colorModel.getBlues(blues);
RGB[] rgbs = new RGB[size];
for (int i = 0; i < rgbs.length; i++) {
rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF,
blues[i] & 0xFF);
}
PaletteData palette = new PaletteData(rgbs);
ImageData data = new ImageData(bufferedImage.getWidth(),
bufferedImage.getHeight(), colorModel.getPixelSize(),
palette);
data.transparentPixel = colorModel.getTransparentPixel();
WritableRaster raster = bufferedImage.getRaster();
int[] pixelArray = new int[1];
for (int y = 0; y < data.height; y++) {
for (int x = 0; x < data.width; x++) {
raster.getPixel(x, y, pixelArray);
data.setPixel(x, y, pixelArray[0]);
}
}
return data;
}
return null;
}
}
17. Create an exact copy of the image
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImageCopyCreation {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Canvas Example");
shell.setLayout(new FillLayout());
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Image image = new Image(display, "yourFile.gif");
Image copy = new Image(display, image, SWT.IMAGE_COPY);
e.gc.drawImage(copy, 10, 10);
e.gc.drawImage(copy, 10, 50);
image.dispose();
copy.dispose();
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. Create an image that has a disabled look
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImageDisable {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Canvas Example");
shell.setLayout(new FillLayout());
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Image image = new Image(display, "yourFile.gif");
Image disable = new Image(display, image, SWT.IMAGE_DISABLE);
e.gc.drawImage(disable, 10, 10);
e.gc.drawImage(image, 10, 50);
image.dispose();
disable.dispose();
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. Create an image that has the grayscale look
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImageGrayScale {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Canvas Example");
shell.setLayout(new FillLayout());
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Image image = new Image(display, "yourFile.gif");
Image disable = new Image(display, image, SWT.IMAGE_GRAY);
e.gc.drawImage(disable, 10, 10);
e.gc.drawImage(image, 10, 50);
image.dispose();
disable.dispose();
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. Create ImageData from PaletteData
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImageDataFromPaletteData {
public static void main(String[] args) {
Display display = new Display();
Color white = display.getSystemColor(SWT.COLOR_WHITE);
Color black = display.getSystemColor(SWT.COLOR_BLACK);
// Create a source ImageData of depth 1 (monochrome)
PaletteData palette = new PaletteData(new RGB[] { white.getRGB(), black.getRGB(), });
ImageData sourceData = new ImageData(20, 20, 1, palette);
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 20; j++) {
sourceData.setPixel(i, j, 1);
}
}
Shell shell = new Shell(display);
final Image source = new Image(display, sourceData);
shell.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
e.gc.drawImage(source, 0, 0, 20, 20, 60, 10, 20, 20);
}
});
shell.setSize(150, 150);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
source.dispose();
display.dispose();
}
}
17. Create Image from byte array
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Cursor example snippet: create a color cursor from a source and a mask
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*
* @since 3.0
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImageFromByteArray {
static byte[] srcData = { (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x00, (byte) 0x00,
(byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x10, (byte) 0x00, (byte) 0x01,
(byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x11, (byte) 0x11, (byte) 0x00, (byte) 0x22,
(byte) 0x01, (byte) 0x10, (byte) 0x33, (byte) 0x00, (byte) 0x11, (byte) 0x10, (byte) 0x02,
(byte) 0x22, (byte) 0x01, (byte) 0x10, (byte) 0x33, (byte) 0x30, (byte) 0x01, (byte) 0x10,
(byte) 0x22, (byte) 0x22, (byte) 0x01, (byte) 0x10, (byte) 0x33, (byte) 0x33, (byte) 0x01,
(byte) 0x10, (byte) 0x22, (byte) 0x22, (byte) 0x01, (byte) 0x10, (byte) 0x33, (byte) 0x33,
(byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x11, (byte) 0x11, (byte) 0x01, (byte) 0x10,
(byte) 0x11, (byte) 0x11, (byte) 0x10, (byte) 0x01, (byte) 0x11, (byte) 0x11, (byte) 0x01,
(byte) 0x10, (byte) 0x11, (byte) 0x11, (byte) 0x10, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x44,
(byte) 0x44, (byte) 0x01, (byte) 0x10, (byte) 0x55, (byte) 0x55, (byte) 0x01, (byte) 0x10,
(byte) 0x44, (byte) 0x44, (byte) 0x01, (byte) 0x10, (byte) 0x55, (byte) 0x55, (byte) 0x01,
(byte) 0x10, (byte) 0x04, (byte) 0x44, (byte) 0x01, (byte) 0x10, (byte) 0x55, (byte) 0x50,
(byte) 0x01, (byte) 0x11, (byte) 0x00, (byte) 0x44, (byte) 0x01, (byte) 0x10, (byte) 0x55,
(byte) 0x00, (byte) 0x11, (byte) 0x11, (byte) 0x10, (byte) 0x00, (byte) 0x01, (byte) 0x10,
(byte) 0x00, (byte) 0x01, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x11, (byte) 0x00,
(byte) 0x00, (byte) 0x11, (byte) 0x11, (byte) 0x11, };
public static void main(String[] args) {
Display display = new Display();
Color white = display.getSystemColor(SWT.COLOR_WHITE);
Color black = display.getSystemColor(SWT.COLOR_BLACK);
Color yellow = display.getSystemColor(SWT.COLOR_YELLOW);
Color red = display.getSystemColor(SWT.COLOR_RED);
Color green = display.getSystemColor(SWT.COLOR_GREEN);
Color blue = display.getSystemColor(SWT.COLOR_BLUE);
// Create a source ImageData of depth 4
PaletteData palette = new PaletteData(new RGB[] { black.getRGB(), white.getRGB(),
yellow.getRGB(), red.getRGB(), blue.getRGB(), green.getRGB() });
ImageData sourceData = new ImageData(16, 16, 4, palette, 1, srcData);
Shell shell = new Shell(display);
final Image source = new Image(display, sourceData);
shell.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.drawImage(source, 20, 20);
}
});
shell.setSize(150, 150);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
source.dispose();
display.dispose();
}
}
17. Creating an Empty Image
Image image1 = new Image(display, 300, 200);
Image image2 = new Image(display, myRect);
17. Creating an Image From a File
Image image = new Image(display, "c:\\temp\\swt.png");
17. Creating an Image From an ImageData
ImageData contains metadata describing an Image. ImageData Constructors:
ConstructorDescriptionImageData(InputStream stream)Creates an ImageData from an image passed as a stream.ImageData(String filename)Creates an ImageData from the image specified by filename.ImageData(int width, int height, int depth, PaletteData palette)Creates an ImageData with the specified width, height, color depth, and palette.ImageData(int width, int height, int depth, PaletteData palette, int scanlinePad, byte[] data)Creates an ImageData with the specified width, height, color depth, palette, scanline pad, and data. data holds the image"s pixel data.
17. Creating an Image From Another Image
To create an image that duplicates another image, or that has a disabled or a grayscale look, use the constructor that takes an Image and a flag:
Image image = new Image(display, otherImage, flag);
The possible values for flag.
ConstantDescriptionSWT.IMAGE_COPYCreate an exact copy of the imageSWT.IMAGE_DISABLECreate an image that has a disabled lookSWT.IMAGE_GRAYCreate an image that has the grayscale look
17. Creating Images
Image Constructors
ConstructorDescriptionImage(Device device, String filename)Creates an image from the specified file nameImage(Device device, InputStream stream)Creates an image from the specified streamImage(Device device, int width, int height)Creates an empty image of the specified width and height (in pixels)Image(Device device, Rectangle bounds)Creates an empty image of the specified sizeImage(Device device, ImageData data)Creates an image from the specified ImageDataImage(Device device, ImageData source, ImageData mask)Creates an image by combining the specified ImageData objectsImage(Device device, Image source, int flag)Creates an image from the specified image, using the value specified by flag
17. Disposal Method Constants
ConstantDescriptionSWT.DM_UNSPECIFIEDUnspecified disposal methodSWT.DM_FILL_NONEDon"t dispose; leave current image in placeSWT.DM_FILL_BACKGROUNDFill the image with the background colorSWT.DM_FILL_PREVIOUSRestore the previous image
17. Drawing Images
MethodDescriptionvoid drawImage(Image image, int x, int y)Draws the image with its top left corner at the point specified by (x, y)void drawImage(Image image, int srcX, int srcY, int srcWidth, int srcHeight, int destX, int destY, int destWidth, int destHeight)Draws the image or part of the image, starting from the point (srcX, srcY), with the width and height specified by srcWidth and srcHeight, respectively, at the point specified by (destX, destY), with the width and height specified by destWidth and destHeight, respectively
17. Draw part of an Image
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImagePartDraw {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Canvas Example");
shell.setLayout(new FillLayout());
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Image image = new Image(display, "yourFile.gif");
System.out.println(image.getImageData().scanlinePad);
image.getImageData().scanlinePad = 40;
System.out.println(image.getImageData().scanlinePad);
e.gc.drawImage(image, 0, 0);
// Determine how big the drawing area is
Rectangle rect = shell.getClientArea();
// Get information about the image
ImageData data = image.getImageData();
// Calculate drawing values
int srcX = data.width / 4;
int srcY = data.height / 4;
int srcWidth = data.width / 2;
int srcHeight = data.height / 2;
int destWidth = 2 * srcWidth;
int destHeight = 2 * srcHeight;
// Draw the image
e.gc.drawImage(image, srcX, srcY, srcWidth, srcHeight, rect.width - destWidth, rect.height
- destHeight, destWidth, destHeight);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. GC example snippet: create an icon (in memory)
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
//package org.eclipse.swt.snippets;
/*
* GC example snippet: create an icon (in memory)
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.PaletteData;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class IconInMemory {
public static void main(String[] args) {
Display display = new Display();
Color red = display.getSystemColor(SWT.COLOR_RED);
Color white = display.getSystemColor(SWT.COLOR_WHITE);
Color black = display.getSystemColor(SWT.COLOR_BLACK);
Image image = new Image(display, 20, 20);
GC gc = new GC(image);
gc.setBackground(red);
gc.fillRectangle(5, 5, 10, 10);
gc.dispose();
ImageData imageData = image.getImageData();
PaletteData palette = new PaletteData(
new RGB[] { new RGB(0, 0, 0), new RGB(0xFF, 0xFF, 0xFF), });
ImageData maskData = new ImageData(20, 20, 1, palette);
Image mask = new Image(display, maskData);
gc = new GC(mask);
gc.setBackground(black);
gc.fillRectangle(0, 0, 20, 20);
gc.setBackground(white);
gc.fillRectangle(5, 5, 10, 10);
gc.dispose();
maskData = mask.getImageData();
Image icon = new Image(display, imageData, maskData);
Shell shell = new Shell(display);
Button button = new Button(shell, SWT.PUSH);
button.setImage(icon);
button.setSize(60, 60);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
icon.dispose();
image.dispose();
mask.dispose();
display.dispose();
}
}
17. Get an ImageData instance from an existing Image
ImageData data = myImage.getImageData();
17. Get ImageData from Image
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.widgets.Display;
public class ImageDataFromImage {
public static void main(String[] args) {
Display display = new Display();
Image image = new Image(display, "yourFile.gif");
ImageData data = image.getImageData();
System.out.println(data.width);
System.out.println(data.height);
if (image != null) image.dispose();
display.dispose();
}
}
17. Images created using different flags for Label
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class ImageCreateForLable {
public static void main(String[] args) {
Image image;
Image copy;
Image disable;
Image gray;
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Show Image Flags");
image = new Image(display, "yourFile.gif");
copy = new Image(display, image, SWT.IMAGE_COPY);
disable = new Image(display, image, SWT.IMAGE_DISABLE);
gray = new Image(display, image, SWT.IMAGE_GRAY);
shell.setLayout(new FillLayout());
// Create labels to hold each image
new Label(shell, SWT.NONE).setImage(image);
new Label(shell, SWT.NONE).setImage(copy);
new Label(shell, SWT.NONE).setImage(disable);
new Label(shell, SWT.NONE).setImage(gray);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
image.dispose();
copy.dispose();
disable.dispose();
gray.dispose();
display.dispose();
}
}
17. Load image from file: an input stream and Class.getResourceAsStream()
Image image = new Image(display, MyClass.getResourceAsStream("/temp/swt.png"));
17. Load image from file: Create an input stream and pass the input stream to the constructor:
Image image = new Image(display, new FileInputStream("c:\\temp\\swt.png"));
17. Paint on an Image
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
public class ImagePaint {
public static void main(String[] args) {
Display display = new Display();
Image image = new Image(display, 20, 20);
Color black = display.getSystemColor(SWT.COLOR_BLACK);
GC gc = new GC(image);
gc.setForeground(black);
gc.drawString("Test", 2, 2);
gc.dispose();
display.dispose();
}
}
17. Rotate Image
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class ImageRotate {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("Canvas Example");
shell.setLayout(new FillLayout());
Canvas canvas = new Canvas(shell, SWT.NONE);
canvas.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
Image image = new Image(display, "yourFile.gif");
ImageData sd = image.getImageData();
ImageData dd = new ImageData(sd.height, sd.width, sd.depth, sd.palette);
int style = SWT.UP;
boolean up = (style & SWT.UP) == SWT.UP;
// Run through the horizontal pixels
for (int sx = 0; sx < sd.width; sx++) {
// Run through the vertical pixels
for (int sy = 0; sy < sd.height; sy++) {
// Determine where to move pixel to in destination image data
int dx = up ? sy : sd.height - sy - 1;
int dy = up ? sd.width - sx - 1 : sx;
// Swap the x, y source data to y, x in the destination
dd.setPixel(dx, dy, sd.getPixel(sx, sy));
}
}
// Create the vertical image
Image vertical = new Image(display, dd);
// Draw the vertical image onto the original GC
e.gc.drawImage(vertical, 10, 10);
vertical.dispose();
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
}
17. SWT can display graphic images from files
SWT can display graphic images from files. It supports the following graphic file formats:
- Graphics Interchange Format (GIF), including animated GIFs
- Portable Network Graphics (PNG)
- Joint Photographic Experts Group (JPEG)
- Tagged Image File Format (TIFF)
- Windows Icon (ICO)
- Windows Bitmap (BMP)
- Windows Bitmap with run-length encoding (RLE)
17. Type Constants
ConstantDescriptionSWT.IMAGE_UNDEFINEDUnknown image typeSWT.IMAGE_BMPBMPSWT.IMAGE_BMP_RLERLESWT.IMAGE_GIFGIFSWT.IMAGE_ICOICOSWT.IMAGE_JPEGJPEGSWT.IMAGE_TIFFTIFFSWT.IMAGE_PNGPNG
17. Use ImageData to create a new image
Image image = new Image(display, data);
Image image = new Image(display, sourceData, maskData);
17. Using code to Create Image
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
public class ImageCreateCode {
public static void main(String[] args) {
final Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Label label = new Label(shell,SWT.NONE);
label.setImage(getCheckedImage(display));
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
static Image getCheckedImage(Display display) {
Image image = new Image(display, 16, 16);
GC gc = new GC(image);
gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW));
gc.fillOval(0, 0, 16, 16);
gc.setForeground(display.getSystemColor(SWT.COLOR_DARK_GREEN));
gc.drawLine(0, 0, 16, 16);
gc.drawLine(16, 0, 0, 16);
gc.dispose();
return image;
}
}