Creating Thumbnail from an Image with transparent background
Hello,
I want to create a thumbnail image of size 200 x 200 pixels from an image of any size.
As the thumbnail is square, I'm centering the image according to size.
The code I'm using is working fine BUT after centering and resizing original image
and writing it to output file the remaining area is of black color.
I want the background should be transparent.
Code I'm using is not using JAI.
Please suggest me the solution.
the code I'm using is as follows:
public static void makeThumbnail(String inFile, String thumbFile ) throws Exception {
Image image = Toolkit.getDefaultToolkit().getImage(inFile);
MediaTracker mediaTracker = new MediaTracker(new Container());
mediaTracker.addImage(image, 0);
mediaTracker.waitForID(0);
int fixedHeight = 200 ;
int fixedWidth = 200 ;
int imageWidth = image.getWidth(null);
int imageHeight = image.getHeight(null);
double imageRatio = 0.25 ;
int thumbHeight = (int)(imageHeight * imageRatio );
int thumbWidth = (int)(imageWidth * imageRatio );
int x = ( fixedWidth - thumbWidth )/2 ;
int y = ( fixedHeight - thumbHeight )/2 ;
System.out.println(thumbHeight + " - " + y );
System.out.println(thumbWidth + " - " + x );
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage thumbImage = new BufferedImage(fixedWidth, fixedHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = thumbImage.createGraphics();
graphics2D.setColor( new Color( 255, 255, 255, 0) );
int rule = AlphaComposite.SRC_IN ;
AlphaComposite ac = AlphaComposite.getInstance(rule, 0.9f);
graphics2D.setComposite(ac);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, x, y, thumbWidth, thumbHeight, null);
// save thumbnail image to OUTFILE
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(thumbFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
int quality = 60 ;
quality = Math.max(0, Math.min(quality, 100));
param.setQuality((float)quality / 100.0f, false);
encoder.setJPEGEncodeParam(param);
encoder.encode(thumbImage);
}
Change this line
BufferedImage thumbImage = new BufferedImage(fixedWidth, fixedHeight,
BufferedImage.TYPE_INT_RGB);
...to use a BufferedImage type that supports transparency like TYPE_INT_ARGB or TYBE_4BYTE_ABGR (I would recommend the latter since your saving the image).
Also, btw, you're not going to like the quality of the thumbnail if the image is reduced by more then half its size.
Similar Messages
-
Framing image with transparent background png frame
hi,
i'm trying to find a way to frame images with transparent background png frames...
what i'm doing now is
1-drawing my image on a panel
2-creating a 2nd image using the frame's filename, stretching this 'frame-image' to a size slighlty larger than that of my main image and drawing the 'frame-image'
the problems with this method are:
1-depending on the width of the frame, the frame sometimes hides parts of the image (thick frame), and sometimes there is a gap between the frame and the image (thin frame).
2-if the image file containing the frame is larger than the frame (Ex: The image is 300x300, the frame is centered in this image and is 200x200; as opposed to the image is 200x200 and the frame takes up all the space), when i position the 'frame-image' near the top left corner of the image i want to frame, the frame appears at the wrong place (shifted down and to the right). This is due to the fact that i'm placing the top corner of the created 'frame-image' and not the frame, who is not in the top corner of my 'frame-image'.
Is there a way to do what i'm trying to do???
My ideas (which i don't know how to achieve are)
1-To 'analyse' my transparent background png file and
1-only keep the frame,
2-calculate the frame's thickness
OR
2-Let java do the analyzing for me and tell it to frame my image with the frame in the png file
please feel free to ask for more explanations if my description/question is confusing,
thanks.Have you looked into the Border interface? If what you really want to do
is put a custom border on a component, you may be able to do it this way.
Anyway, here is some code that stacks and centres 2 images. It's not hard to do.
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class Example extends JComponent {
private BufferedImage backgroundImage;
private BufferedImage foregroundImage;
public Example(BufferedImage backgroundImage, BufferedImage foregroundImage) {
this.backgroundImage = backgroundImage;
this.foregroundImage = foregroundImage;
public Dimension getPreferredSize() {
int w = backgroundImage.getWidth();
int h = backgroundImage.getHeight();
return new Dimension(w, h); //assuming this is bigger
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int w = getWidth();
int h = getHeight();
//paint both, centred
int x0 = (w-backgroundImage.getWidth())/2, y0 = (h-backgroundImage.getHeight())/2;
g.drawImage(backgroundImage, x0, y0, null);
int x1 = (w-foregroundImage.getWidth())/2, y1 = (h-foregroundImage.getHeight())/2;
g.drawImage(foregroundImage, x1, y1, null);
public static void main(String[] args) throws IOException {
URL url1 = new URL("http://weblogs.java.net/jag/Image54-large.jpeg");
URL url2 = new URL("http://weblogs.java.net/jag/DukeSaltimbanqueSmall.jpeg");
JComponent comp = new Example(ImageIO.read(url1), ImageIO.read(url2));
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(comp);
f.pack();
SwingUtilities.invokeLater(new Runnable(){
public void run() {
f.setLocationRelativeTo(null);
f.setVisible(true);
} -
Printing Images with Transparent Background
Sorry if this question has already been asked, but I couldn't find anything similar to it in a search through the archives.
I have a couple of images with transparent backgrounds in a document, much like the shells and the blue flowers in the "Classic Brochure" template in Pages 2.0.1. These images show up perfect on the screen, and when printed as .pdf files, but when I print to either an hp color laserjet 4600 or an hp laserjet 1320, the images show up with a clear box around them; the colors under the box (where it should be transparent) are faded and slightly blurred. This happens both with my document, and the unaltered "Classic Brochure" template. I've tried moving various objects backwards and forwards, but it doen't seem to have any effect. It even happens with one of the text boxes I have in the document.
Another odd thing is that the printed "box" isn't the same size as the box that appears when you click on the object in the document. It's a bit bigger. I've seen other posts about problems with hp printers, but I'm not sure it's related. Any insight would be appreciated.
MAF
iMac Intel Core Duo Mac OS X (10.4.7)http://indesignsecrets.com/eliminating-ydb-yucky-discolored-box-syndrome.php
Bob -
Image with transparent background als foreground of a button
I'd like to build an app with buttons using the phone's accent Color as Background and an Image with transparent Background as foreground of the button. It should look like the tiles on the start screen of WP8.1.
The following code doesn't work (no foreground appears)
<Button x:Name="myButton" Background="{ThemeResource PhoneAccentBrush}">
<Button.Foreground>
<ImageBrush ImageSource="/Assets/myImage.png"/>
<Button.Foreground>
</Button>
Are there any ideas?
Thanks
MartinHi mfv_technet,
The Foreground property is used to get or set a brush that describes the foreground color. So we can not bind the Foreground to a image,
if I do not misunderstand you, in my mind if we want to set the button look like the tiles on the start screen of WP8.1, maybe you can try to refer to the following xaml:
<Button x:Name="myButton" Foreground="Red" Background="{ThemeResource PhoneAccentBrush}" Margin="116,136,0,363" Width="195" Height="141">
<Button.Content>
<StackPanel Orientation="Vertical">
<Image Source="/Assets/myImage.png" Width="80" Height="80"></Image>
<TextBlock Text="Button"></TextBlock>
</StackPanel>
</Button.Content>
</Button>
The result:
If I have misunderstood you, please feel free to let me know.
Best Regards,
Amy Peng
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click
HERE to participate the survey. -
Images with transparent backgrounds in MDM
I've got several images in MDM with transparent backgrounds, yet when i look at these in image manager (or thumbnails in data manager) they look terrible. The transparency is black for example, among other issues. These images are all okay in photoshop, they have been saved as .png and imported through the data manager.
Has this import ruined these image files on the way in? When my search engines etc extract the images, what of the transparencies?Hi Adam,
MDM makes use of Internet Explorer quite frequently. I can imagine that this engine is also used to display images in MDM. However, Internet Explorer in version 6 does not support transparency in PNG images. That is why the black background occurs.
Since your images after upload are only saved in a binary object in the database, you should not encounter any data loss when using the same images. If you need to create variants, I would consider using Photoshop for the creation of those.
I hope that helps you further.
Best regards
Christian -
Image with transparent background shows up with a white background in ID
Amateur needs help.
I have a copy of a logo with a transparent background. I made the (white) background transparent in PS by creating a layer from background and then selecting the white color in the background and deleting it. This has always worked in the past. But when I place this image into ID, it shows up with a white background. I have tried saving as a PSD, TIF, JPG, etc. I cannot get it to work.
I normally research these things until I find an answer, but I am on a tight deadline. Thanks!I totally forgot to put that in my post. Yes, I am putting logos with transparent backgrounds in front of colored rectangles. That's how I noticed that this one logo is showing up with a white background. The weird thing is that the other two logos are fine. I did find a different version of this logo and this one works fine. The one that works fine is a JPG and the one that shows up with a white background is a JPG.
-
Images with transparent background layers
I have a number of .psd files with transparent backgrounds. If I import them into Aperture, they show up in the Browser and Viewer with black backgrounds. If I drag them into a Book, some of them behave as though transparent, but some retain the black background.
I can't see any difference in the files themselves. They were all created by the same means. Why would some of them lose their transparency in Aperture and some retain it?Aperture doesn't support transparency at this time.
I'm pretty surprised that any of them behave as though transparent.
You should make the Image backgrounds the same color as the book pages to achieve a transparency effect.
DLS -
Image with transparent background changes surrounding fill color when PMS...
Hello.
I have a .PSD image I'm using in InDesign CS3. It's a greyscale image with a transparent background. When I bring it into InDesign and set the background color of the image box to a Pantone and then print it, the PMS color within the area of the .PSD image size changes color compared to the rest of the page. But, when the same document is printed, but with "All Spot to Process" via the Ink Manager, the page prints fine. I get the same results on a number of different Canon and Xerox proofing printers. I have uploaded a PDF to my web server showing an example of the results I'm getting the PDF can be found here:
http://theboyk.net/temp/PMSvsCMYK.pdf
The first page is the document printed normally. You can see the color change in the green (Pantone Green). The second page is the same document printed with "All Spot to Process" via Ink Manager.
Does anyone know why this happens when I leave it as printing a spot color?
Any advice would be appreciated!
Thanks,
Kristin.I totally forgot to put that in my post. Yes, I am putting logos with transparent backgrounds in front of colored rectangles. That's how I noticed that this one logo is showing up with a white background. The weird thing is that the other two logos are fine. I did find a different version of this logo and this one works fine. The one that works fine is a JPG and the one that shows up with a white background is a JPG.
-
How to insert image with transparent background?
I have several logos saved at .GIFs with transparent backgrounds that I would like to import into my dashboard, but it seems that the image component only supports JPEG. Is there a way to import images while maintaining their transparency?
Well, you CAN insert GIFs or other image formats. But I have yet to figure out a way to take a GIF with a transparent background and import it into my Xcelsius while preserving the transparency. The transparent background always just defaults to white.
This is a crucial feature as I have some logos I want to use that are circular. But if I can't give them a transparent background, it drastically limits their placement options.
I know that flash does support transparency, so am I missing something here? -
Creating images with transparent backgrounds
Hello all,
I've got a swing app drawing program where you have multiple layers, with each layer containing many components that can be moved and resized. So, in the most simple form, I have a JComponent which has a list of images to be drawn. If I setOpaque to false, the background (and other layers) can be seen through the empty spaces of this component, as expected.
The problem was that once the number of components grew above 300, performance started suffering. So I decided to optimize it. Instead of redrawing all of the components each time I need to paint, I 'cache' that layer by drawing all of the components in a layer onto an Image's graphic. Then I do a 'graphics.drawImage(cachedImage);' in my main JComponent's paint method.
Very fast, but now I can't see the background (and other layers) beneath the topmost one.
So now the question. Is there a way to preserve the 'setOpaque(false)' call when painting to the image. To be more specific, I want an image that is transparent except for graphics that I've drawn into it. I've even tried first filling the image with a 'new Color(255,255,255,0)', but I'm still getting an opaque image.
thanks for any help,
Steven
A Dynamic character with an ability to survive certain death, and a questionable death scene leaving no corpse? Face it, we'll never see her again... - Riff from Sluggy FreelanceUsing a TYPE_INT_ARGB BufferedImage worked beautifully. I had played around with Image for hours, but it never occurred to me that BufferedImage would be needed. :)
many, many thanks,
Steven -
How do I get picture control to display PNG images with transparent background?
I have an image of a robot arm looking from the top with a transparent background and saved as PNG. When I drag the image directly to LabVIEW front panel, the image shows properly with the transparent background, but I want to manipulate it such as rotate the image. I used the Read from PNG.vi to read the image to a picture control, but the background isn't transparent anymore. Am I missing something?
Please help.unclebump gets 5 stars for referring you to a document that I wrote.
Incidentally, I wrote it years back, for LabVIEW 7.0. A couple of notes to summarize:
The picture control doesn't "really" support transparency. However, the image data type supports masking, and stores the alpha channel, if present in your image data. So you use the "Create Mask By Alpha.vi" referenced in that document to mask out pixels whose transparency is above a certain level. It does not support partial transparency. You could try to implement your own blending algorithm based on the picture control's current pixel values, and the image data's RGB value and transparency value, but it would probably be very slow.
Also, that VI ships with 8.0 and later. I don't know if it's on the palettes but it lives here: vi.lib\picture\picture.llb\Create Mask By Alpha.vi
Good luck! -
How to create a live trace object with transparent background?
Hi, I am trying to create a live trace object of my logo in ai. The logo is coming from photoshop on a transperent background, and it is all black. What I want to do is to bring it into ai and make it an object for obvious reasons. The problem I have had is that when I live trace it, the live trace leaves a white background which then overlaps with other objects in my ai file. Is there a way to live trace while preserving the transparent area or possibly better, to not include white space in the live trace? Thanks in advance!
Yep open the properties for live trace (Object>Live Trace>Tracing options). You will find a checkbox for ignore white.
-
Save image with transparent background
Hello,
I use the IMAQ vis in labview to cut out from a tif image an object that appears on a grey spotty background and paste the object on a "clean" background. Currently the "clean" background is white. The image is saved as a tif file and read in photoshop where the object is rotated to match a predefined orientation. The problem is that the white background also rotates which is not desirable. When the manipulation is done entirely in photoshop (cutout + pasting + rotation), the clean background and the object are placed in different layers. Is there a way to do this in Labview, that is to create an image where the background and the object would be read by photoshop as being in different layers? Alternatively, can the clean background be made transparent in labview. I understand the png files can have a transparent background. How can I specify that the background is transparent instead of white?
Thank you for your help
Jean-Michel MaarekHi Jean-Michel,
It appears that this issue is already being addressed in another forum post.
Vu -
Photoshop images with transparent background
Hello all! I've searched for this topic in previous threads, but was unsuccessful. Therefore I'll ask the question again:
If I create a Photoshop image with a transparent background, why does it import into iWeb with a WHITE background? Is there a setting in iWeb where I can drag and drop images and not have a white background on the image? Thanks so much in advance!Captain Maniac wrote:
Hello all! I've searched for this topic in previous threads, but was unsuccessful. Therefore I'll ask the question again:
If I create a Photoshop image with a transparent background, why does it import into iWeb with a WHITE background? Is there a setting in iWeb where I can drag and drop images and not have a white background on the image? Thanks so much in advance!
Hi There,
The most likely candidate here is that the file format you're using doesn't support transparency. Try saving the Photoshop file in a different format such as PNG or GIF which support transparency.
Hope this helps
J.C -
Drawing images with transparent background on any AWT container control.
I have an AWT applet with some background image.
There is another image say of a size of an icon which
has a transparent background. This image can be
dragged anywhere on the applet.
I am using a panel of a size of an icon and drawing the
image on it. The whole panel is dragged when the user
drags the image.
The problem over here is, though the image has a
transparent background it is not appearing transparent
on the applet because the background of its container
i.e., the panel which is dragged along, itself is not
transparent.
My question is : "Is there a way to make a control, like a panel, background transparent in AWT or some other way that can produce a similar effect in AWT ?".
Please help me out.
Thanks.Maybe the best way is to create your own component ( extending Component ) and then implementing paint() to do what you need.
Maybe you are looking for
-
For a few months, I have been unable to print from Firefox. I assumed it was a setting or something on my network, but today figured out it's my old printer driver that is no longer compatible. There is no new driver, nor will there be one. I love my
-
Lightroom 1.2 has lost Photoshop CS3 as external editor
In Lightroom 1 I used Photoshop CS2 as external editor and lightroom has found it with the first choice of external editors. In Lightroom 1.1 I used Photoshop CS3 as external editor and lightroom has also found CS3 in the first choice of external edi
-
Hi, What are the exceptions in function module. Thanks in advance
-
Updating Air Application without prompt
I am considering using Air for a kiosk application. One potential issue I see is that when you update, my research shows that it requires someone to click an "Accept" button to perform the update. I was wondering is there any way around this? If t
-
Finder and header bar icons disappear
Hello everyone, Some icons disappear from my header bar and the finder, please see the screenshot: MacOS: Version 10.8.4 Short before that happen, my disk was full and I removed some video/music in order to get some free space again. I don't know if