Loading a BMP in an Eclipse Plugin Perspective using SWT - java

I have a BMP in a bytearray. I would like to display the BMP in an Eclipse Plugin using SWT.
If I want to display the BMP using swing - it can be done as follows:
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(new ByteArrayInputStream(getLocalByteArray()));
} catch (IOException ex) {
}
JLabel jLabel = new JLabel(new ImageIcon(bufferedImage));
JPanel jPanel = new JPanel();
jPanel.add(jLabel);
this.add(jPanel);
Update:
The BMP will be represented as a byte array. This is pre requisite of this.
How do I do this in an Eclipse Plugin using SWT? Note I am using a Perspective.

An SWT Image can directly be created from an input stream. Several data formats are supported, including Windows format BMPs.
For example:
Image image = new Image( display, new ByteArrayInputStream( ... ) );
The resulting image can then be set on a Label or used elsewhere.

You can simply specify the file in the Image constructor and then set it to a Label.
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Label label = new Label(shell, SWT.NONE);
Image image = new Image(display, "image.bmp");
label.setImage(image);
shell.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
image.dispose();
}
Remember that you have to dispose() of the image yourself to not create a memory leak.

OK - I figured it out. As the code is short I've included the context:
public void createPartControl(Composite parent) {
try {
BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(getLocalByteArray()));
ImageData imageData = new ImageData(inputStream);
Image image = ImageDescriptor.createFromImageData(imageData).createImage();
// Create the canvas for drawing
Canvas canvas = new Canvas( parent, SWT.NONE);
canvas.addPaintListener( new PaintListener() {
public void paintControl(PaintEvent e) {
GC gc = e.gc;
gc.drawImage( image,10,10);
}
});

Related

SWT Transparent pixels changed to white

I'm trying to create a transparent image and then draw another image onto it that contains transparent/translucent pixels. After the image is added translucent pixels are set to white in comparison to being being a mixture of the colour and alpha. This is causing there to be a white outline around the image.
The image has to be shown on a ToolBar as a ToolItem with transparent pixels.
Is it possible to draw an image with transparency without it changing the transparent pixels to white?
Overlay Image
Processed Image
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setSize(285,305);
// Create a transparent image
final Image transparentImage = new Image(null, 256, 256);
final ImageData imageData = transparentImage.getImageData();
imageData.transparentPixel = imageData.getPixel(0, 0);
transparentImage.dispose();
// Create an image with the transparent data
final Image processedImage = new Image(Display.getCurrent(),
imageData);
// Get the image to draw onto the transparent image
final Image overlayImage = new Image(display, "overlay_image.png");
final GC imageGC = new GC(processedImage);
imageGC.setAntialias(SWT.ON);
imageGC.drawImage(overlayImage, 0, 0);
imageGC.dispose();
// Create the components and add the image
final ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.BORDER);
final ToolItem item = new ToolItem(toolBar, SWT.NONE);
item.setImage(processedImage);
toolBar.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
overlayImage.dispose();
display.dispose();
The problem is with the image you used, it has a transparent color white, so if you want to use that image, or you change transparent color manipulating the image with a program (GIMP?), or you can give the same transparent color to both the images, so first take the transparent color from the image "overlay_image.png" at position (0,0) and only alter set the same transparent color for the second (transparent) image. this is the working code with your image:
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.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
public class TestTransparency {
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setSize(285,305);
final Image overlayImage = new Image(display, "overlay_image.png");
final ImageData imageDataOverlay = overlayImage.getImageData();
imageDataOverlay.transparentPixel = imageDataOverlay.transparentPixel;
// Create a transparent image
final Image transparentImage = new Image(display, 800, 600);
final ImageData imageData = transparentImage.getImageData();
imageData.transparentPixel = imageDataOverlay.transparentPixel;
transparentImage.dispose();
final Image processedImage = new Image(Display.getCurrent(),
imageData);
final Image overlayImage2 = new Image(Display.getCurrent(),
imageDataOverlay);
final GC imageGC = new GC(processedImage);
imageGC.setAntialias(SWT.ON);
imageGC.drawImage(overlayImage2, 0, 0);
imageGC.dispose();
// Create the components and add the image
final ToolBar toolBar = new ToolBar(shell, SWT.FLAT | SWT.BORDER);
toolBar.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
final ToolItem item = new ToolItem(toolBar, SWT.NONE);
item.setImage(processedImage);
toolBar.pack();
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
overlayImage.dispose();
display.dispose();
}
}
Please note that, using GIMP manipulating your image:
or using a good transparent image like this: http://www.stickpng.com/img/icons-logos-emojis/tech-companies/youtube-play-logo your code works fine!

SWT CTabFolder: Add watermark (in case of no tabs)

I am looking for a method to add a kind of watermark to a SWT CTabFolder.
My goal is that the tab folder does not look as "boring" if there are no tabs present.
I am aware of the setBackgroundImage method of CTabFolder. Unfortunately, this seems to be non adjustable and can only display an image in "tiled" format.
Do you know of any way to add a centered image to an empty tab folder?
You'll have to add your own Listeners for SWT.Paint, and SWT.Resize. Then draw your Image on the GC. Here is an example:
public static void main(String[] args)
{
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setText("StackOverflow");
shell.setLayout(new FillLayout());
final Image image = new Image(null, "info.png");
final CTabFolder folder = new CTabFolder(shell, SWT.TOP);
folder.addListener(SWT.Paint, new Listener()
{
#Override
public void handleEvent(Event event)
{
if (image.isDisposed())
return;
Rectangle parentSize = folder.getBounds();
int tabHeight = folder.getTabHeight();
Rectangle imageSize = image.getBounds();
event.gc.drawImage(image, (parentSize.width - imageSize.width) / 2, (parentSize.height - imageSize.height + tabHeight) / 2);
}
});
folder.addListener(SWT.Resize, new Listener()
{
#Override
public void handleEvent(Event event)
{
folder.redraw();
}
});
CTabItem item = new CTabItem(folder, SWT.CLOSE);
item.setText("TEST");
Composite content = new Composite(folder, SWT.NONE);
content.setLayout(new FillLayout());
new Label(content, SWT.NONE).setText("bla");
item.setControl(content);
shell.pack();
shell.setSize(400, 200);
shell.open();
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
{
display.sleep();
}
}
display.dispose();
image.dispose();
}
Looks like this when you have a CTabItem:
And like this when you close the item:

print swt component even if hidden by scrollbar

I try to print a swt TreeViewer to png file. With:
Tree tree = treeViewer.getTree();
Image image = new Image(display, tree.getSize().x, tree.getParent().getSize().y);
GC gc = new GC(image);
System.out.println(new File(pathToSave).getAbsolutePath());
tree.print(gc);
ImageLoader loader = new ImageLoader();
loader.data = new ImageData[] { image.getImageData() };
loader.save(pathToSave, SWT.IMAGE_PNG);
gc.dispose();
image.dispose();
the png contains only the visible part of the tree. The tree has a scrollbar because it contains more elements than fit on the form.
I would like to print the tree with all elements visible and without scrollbar. Any ideas?
On swing components i could use .paintall().. swt components don't seem to know that.
First, the size of the image should have the size the tree would have without scrolls, and not the current size. For that you should use computeSize(SWT.DEFAULT, SWT.DEFAULT, true). Then you should resize the tree that size, print, and then resize it back. Since you don't want users to notice that, during this operation you should disabled draws with setRedraw(false).
Here is a full snippet that does all this:
public static void main(String[] args) {
final Display display = new Display();
final Shell shell = new Shell(display);
shell.setLayout(new FillLayout());
Composite composite = new Composite(shell, SWT.NONE);
composite.setLayout(new FillLayout());
final Tree tree = new Tree(composite, SWT.NONE);
for (int i = 0; i < 100; i++) {
final TreeItem treeItem = new TreeItem(tree, SWT.NONE);
treeItem.setText(String.format("item %d long name", i));
}
tree.addListener(SWT.DefaultSelection, new Listener() {
#Override
public void handleEvent(Event event) {
tree.getParent().setRedraw(false);
final Point originalSize = tree.getSize();
final Point size = tree.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
final Image image = new Image(display, size.x, size.y);
final GC gc = new GC(image);
tree.setSize(size);
tree.print(gc);
tree.setSize(originalSize);
final ImageLoader loader = new ImageLoader();
loader.data = new ImageData[]{image.getImageData()};
final String pathToSave = "out.png";
System.out.println(new File(pathToSave).getAbsolutePath());
loader.save(pathToSave, SWT.IMAGE_PNG);
gc.dispose();
image.dispose();
tree.getParent().setRedraw(true);
}
});
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
Press enter to save the file.

how to save java swing ImageIcon image to file?

I am using the following code for displaying the Image on the swing frame.
ImageIcon icon = new ImageIcon("image.jpeg");
icon.getImage().flush();
jLabel3.setIcon( icon );
I need a button which when clicked upon will save the image with a jpeg/png extension .
I usually do something like this
Image img = icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_BYTE_ARGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, 0, 0, null);
g2.dispose();
ImageIO.write(bi, "jpg", new File("img.jpg"));
also try other image types like BufferedImage.TYPE_INT_RGB, checkout BufferedImage
you may also want to read this Writing/Saving an Image
hope it works for you
consider useing ImageIO.write(Image img, String type, File file) for writeing a Image to the filesystem.
You get an Image object from the ImageIcon with getImage()
You have to Implement a ActionListener for the Button, and then you are ready to go
So the first part is implementing actionlistener so the button works when you click it. The JButton.
The second part is saving the image which i use ImageIo.write
See code below
public class MyFrame extends JFrame implements ActionListener {
private JButton button1 = new JButton("Click me!");
public MyFrame() {
button1.addActionListener(this);
//... add buttons to frame ...
}
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src == button1) {
string imagename = icon.getDescription;
try {
// retrieve image
BufferedImage bi = icon.getImage();
File outputfile = new File("saved.png");
ImageIO.write(bi, "png", outputfile);
} catch (IOException e)
{
//catch the exception here
}
}
}
}

ImageLoading in JPanel using JFileChooser

I am trying to load an image into a JPanel using JFileChooser. But when I try to run the program and load a selected image nothing happens in the JPanel. I am attaching the source code snippet here:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
FileFilter filter = new FileNameExtensionFilter("Image files","jpeg","jpg");
fileChooser.setFileFilter(filter);
int result = fileChooser.showOpenDialog(null);
if(result == fileChooser.APPROVE_OPTION){
imgFile = fileChooser.getSelectedFile();//imgFile is File type
try{
myPicture = ImageIO.read(imgFile);//myPicture is BufferedImage
JLabel picLabel = new JLabel(new ImageIcon( myPicture )) ;
imagePanel.add( picLabel );
imagePanel.repaint();
System.out.println("You have selected "+imgFile);
}catch(Exception e){
e.printStackTrace();
}
}
}
Can anyone shed light on this?
The problem is that I have added two panels in my frame.
You might compare what you're doing with this complete example that uses two panels: a file chooser on the left and a display panel on the right.
I think this might help you...
Object selectedItem = jComboBox14.getSelectedItem();
ImageIcon picturetoInsert = new ImageIcon(selectedItem.toString());
JLabel label = new JLabel("", picturetoInsert, JLabel.CENTER);
JPanel panel = new JPanel(new GridLayout(1, 1));
panel.add(label, BorderLayout.CENTER);
jInternalFrame22.getContentPane();
jInternalFrame22.setContentPane(panel);
jInternalFrame22.setVisible(true);
Why don you try with the paint component?
class imagePanel extends JPanel
{
BufferedImage image;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(image != null)
{
g.drawImage(image, 0, 0, this);
}
}
}
There could be a few reasons for this. You could try
imagePanel.invalidate()
before the repaint call to force it to redraw.
Or possibly the label is to small and needs resizing since there may not have been an image before. You could try invoke the
frame.pack();
method to get the frame to recompute its component sizes.
Or you could try force the size of the label (setting its min size) to ensure it has enough space to show the image.

Categories