How can i rotate a PNG photo and keep the transparent background?

current i use this method to rotate a photo, but the transparent background is lost.
what can I do ?
public CreateRotationPhoto(String photofile,String filetype,int rotation_value,String desfile){
             File fileIn = new File(photofile);
           if (!fileIn.exists()) {
               System.out.println(" file not exists!");
               return;
           try {
                   InputStream input = new FileInputStream(fileIn);
                   JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(input);
                   BufferedImage imageSrc = decoder.decodeAsBufferedImage();
                   int width = imageSrc.getWidth();
                   int height = imageSrc.getHeight();
                   BufferedImage src = ImageIO.read(input);
                   int width = src.getWidth(); //????? 
                        int height = src.getHeight(); //????? 
                   Image img = src.getScaledInstance(width, height,
                           Image.SCALE_FAST);
                   BufferedImage bi;
                   int fill_width=0;
                   int fill_height=0;
                   if (rotation_value==1||rotation_value==3){
                        bi = new BufferedImage(height, width,BufferedImage.TYPE_INT_RGB);
                        fill_width=height;
                        fill_height=width;
                   else{
                        bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
                        fill_height=height;
                        fill_width=width;
                        //BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                   input.close();
                   System.out.println(photofile);
                   File fileOut = new File(desfile);
                   //File fileOut = new File("c:/Host1.PNG");
                   OutputStream output = new FileOutputStream(fileOut);
                   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
                   JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
                   param.setQuality(0.90f, false);
                   encoder.setJPEGEncodeParam(param);
                   Graphics2D biContext =bi.createGraphics();
                  biContext.setColor(Color.white);
                   biContext.fillRect(0,0,fill_width,fill_height);
                   int frame_width,frame_height;
                 if (rotation_value==1||rotation_value==3){
                        frame_width=height;
                        frame_height=width;
                   }else{
                        frame_width=width;
                        frame_height=height;
                   int x=0,y=0;
                   if (rotation_value==2){
                        x=frame_width;
                        y=frame_height;
                   if (rotation_value==0){
                         x=frame_width;
                         y=frame_height;
                   if (rotation_value==1){
                            x=frame_height;
                             y=frame_height;
                   if (rotation_value==3){
                                x=frame_width;
                             y=frame_width;
                   double rotate=0;
                   if (rotation_value==0){
                         rotate=Math.PI *2;
                   if (rotation_value==1){
                        rotate=Math.PI / 2;
                   if (rotation_value==2){
                        rotate=Math.PI;
                   if (rotation_value==3){
                        rotate=Math.PI*1.5;
                   int x=0,y=0;
                   if (rotation_value==2){
                        x=width;
                        y=height;
                   if (rotation_value==1){
                            x=height;
                             y=height;
                   if (rotation_value==3){
                                x=width;
                             y=width;
                   double rotate=0;
                   if (rotation_value==1){
                        rotate=Math.PI / 2;
                   if (rotation_value==2){
                        rotate=Math.PI;
                   if (rotation_value==3){
                        rotate=Math.PI*1.5;
                   System.out.println(Integer.toString(x)+"|x|"+Integer.toString(y)+"|y|"+Double.toString(rotate));
                   biContext.rotate(rotate, x / 2, y / 2);
                   biContext.drawImage(src, 0, 0, null);
                   biContext.dispose();
                   System.out.println("123123123123");
                   try{
                           ImageIO.write(bi, filetype, output);
                           //ImageIO.write(bi, filetype, "c:/Host.PNG");
                           output.close();
                      }catch (IOException e) {
                          System.err.println(e);
                  // encoder.encode(bi);
                   //output.close();
            } catch (Exception e) {
                     e.printStackTrace();
      }

Using this BufferedImage.TYPE_INT_RGB for the type will eliminate any transparency in
your image. Try BufferedImage.TYPE_INT_ARGB.
Image file: Bird.gif
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.*;
public class Rotate implements ChangeListener
    BufferedImage image;
    JLabel label;
    JSlider slider;
    public Rotate(BufferedImage orig)
        // make transparent background
        Color toErase = new Color(248, 248, 248, 255);
        image = eraseColor(convertImage(orig), toErase);
    public void stateChanged(ChangeEvent e)
        int value = slider.getValue();
        double theta = Math.toRadians(value);
        BufferedImage rotated = getImage(theta);
        label.setIcon(new ImageIcon(rotated));
    private BufferedImage getImage(double theta)
        double cos = Math.cos(theta);
        double sin = Math.sin(theta);
        int w = image.getWidth();
        int h = image.getHeight();
        int width  = (int)(Math.abs(w * cos) + Math.abs(h * sin));
        int height = (int)(Math.abs(w * sin) + Math.abs(h * cos));
        BufferedImage bi = new BufferedImage(width, height, image.getType());
        Graphics2D g2 = bi.createGraphics();
        g2.setPaint(new Color(0,0,0,0));
        g2.fillRect(0,0,width,height);
        AffineTransform at = AffineTransform.getRotateInstance(theta, width/2, height/2);
        double x = (width - w)/2;
        double y = (height - h)/2;
        at.translate(x, y);
        g2.drawRenderedImage(image, at);
        g2.dispose();
        return bi;
    private BufferedImage convertImage(BufferedImage in)
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice gd = ge.getDefaultScreenDevice();
        GraphicsConfiguration gc = gd.getDefaultConfiguration();
        BufferedImage out = gc.createCompatibleImage(in.getWidth(), in.getHeight(),
                                                     Transparency.TRANSLUCENT);
        Graphics2D g2 = out.createGraphics();
        g2.drawImage(in, 0, 0, null);
        g2.dispose();
        return out;
    private BufferedImage eraseColor(BufferedImage source, Color color)
        int w = source.getWidth();
        int h = source.getHeight();
        int type = BufferedImage.TYPE_INT_ARGB;
        BufferedImage out = new BufferedImage(w, h, type);
        Graphics2D g2 = out.createGraphics();
        g2.setPaint(new Color(0,0,0,0));
        g2.fillRect(0,0,w,h);
        int target = color.getRGB();
        for(int j = 0; j < w*h; j++)
            int x = j % w;
            int y = j / w;
            if(source.getRGB(x, y) == target)
                source.setRGB(x, y, 0);
        g2.drawImage(source, 0, 0, null);
        g2.dispose();
        return out;
    private JLabel getLabel()
        label = new JLabel(new ImageIcon(image));
        return label;
    private JSlider getSlider()
        slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 0);
        slider.addChangeListener(this);
        return slider;
    public static void main(String[] args) throws IOException
        String path = "images/Bird.gif";
        ClassLoader cl = Rotate.class.getClassLoader();
        InputStream is = cl.getResourceAsStream(path);
        Rotate rotate = new Rotate(ImageIO.read(is));
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setBackground(Color.pink);
        f.getContentPane().add(rotate.getLabel());
        f.getContentPane().add(rotate.getSlider(), "South");
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
}

Similar Messages

  • How can I start anew with Photos and clear the (minimal) stuff it has uploaded

    I've about had it up to here with this new Photos scheme. I reorganised my Aperture libraries on both my iMac and MBA in preparation for this, delayed turning Photos on for a couple of days until I thought everything was ready based upon the limited advice that was out there, and then got stuck in an endless loop of "uploading" and "preparing" every time I opened Photos. There are 19,975 images in my Aperture library on the iMac. I was stuck at Uploading at anywhere between that number and 19,000 with no progress after hours of waiting. I tried all the tricks mentioned here including re booting, restarting the app, repairing/rebuilding the database, killing the "cloudd" process, etc.today Today when I restarted Photos, it now said I had 23,775 images to upload- 4000
    more than I have-and of course it got stuck there, like it has for the last week.
    I copied the previous Aperture library (pre Photos migration)back to my iMac and opened it in Aperture. Thankfully, all the photos I had taken on my iPhone this week during this Photos clusterphuck transition were in the Aperture Stream so I didn't lose any of those. I'm willing to give this whole thing one more shot. So  i need some advice. How can I start anew with Photos and clear the (minimal) stuff it has uploaded (about 6000 of 19,000 images in the last 7 days) ? If I simply delete the Photos.photolibrary file will that do the trick and lt me start a new fresh library using?
    <Re-Titled By Host>

    How can I start anew with Photos and clear the (minimal) stuff it has uploaded (about 6000 of 19,000 images in the last 7 days) ? If I simply delete the Photos.photolibrary file will that do the trick and lt me start a new fresh library using?
    It is hard to say from your post, why the migration did not succeed in your case.
    by "stuck on upload" do you mean, you opened the Aperture library in Photos, and Photos converted it to a Photo Library, and then the upload to iCloud Photo Library did hang?  Or did already the upgrade to the Photo Library fail?
    If you want the Aperture library to upload to iCloud Photo Library, it needs to be on a disk formatted MacOS Extended (Journaled) and the original image files must not be referenced. Referenced originals will not upload.
    Also, the upload may hang, if you do not have enough free iCloud storage, orr if one of the videos or photos in your library is in an unsupported format or corrupted.
    To start over, try to repair and rebuild the Aperture library before opening it in Photos. Try all Aperture Library First Aid options - starting with repairing the permissions.  (Repairing and Rebuilding Your Aperture Library: Aperture 3 User Manual)
    If I simply delete the Photos.photolibrary file will that do the trick and lt me start a new fresh library using?
    You will have to delete the photos that are already in icloud too; otherwise you are risking duplicates.
    Can you launch Photos at all?  If yes, delete all photos in Photos and empty the Recently Deleted album. Wait for the deletion to sync to iCloud. Then delete the Photos.photolibrary.

  • I HATE THE NEWEST ITUNES UPDATE. how can i uninstall this latest update and keep the older version??

    I HATE THE NEWEST ITUNES UPDATE. how can i uninstall this latest update and just use the previous version??

    I have same prob as Mizz Gibbs.
    itunes = 11.1.3.8
    OS = Win 7 Home Preimum Service Pack 1 (with latest updates applied)
    thx for any help you can offer ...

  • HT4889 How can I transfer my iPhoto photos and iTunes library to my new iMac?

    How can I transfer my iPhoto photos and iTunes library to my new iMac?

    If the Migration Assistant won't do it, move them over as you would any other folder; they're located in the Pictures and Music folders of your home folder by default. The iPhoto library needs to be transferred via a drive, partition, or disk image formatted as Mac OS Extended or through an AFP network share.
    (72915)

  • How can i delete all my photos and music easily?

    how can i delete all my photos and music easily?
    I have changed to a new macbook and given the old one to my partner (generous?) and want to delete a lot of my stuff on the old one (iphoto and itunes) without losing safari and mail data, settings etc so I dont want to a clean reinstall.
    Jo

    Jhunior wrote:
    HI
    I need help
    Please
    But i need talk too you, i don´t speck english very well, I´m a Brazilian Guy
    Then post your question in your native language.  This is a multi-lingual forum.

  • Hello, I recently bought an iPad Air. Can anyone Please tell me How can in Transfer files like photos and videos from my win 8 computer to ipad ?

    Hello, I recently bought an iPad Air. Can anyone Please tell me How can in Transfer files like photos and videos from my win 8 computer to ipad ?

    Sync photos to iPad
    http://support.apple.com/kb/ht4236

  • I want to remove the monitor from my 17" Macbook Pro 2008 to use as an external for my Macbook Pro 15" 2012. How can I convert lvds to Thunderbolt and power the monitor?

    I want to remove the monitor from my 17" Macbook Pro 2008 to use as an external for my Macbook Pro 15" 2012. How can I convert lvds to Thunderbolt and power the monitor?

    It's almost impossible.  The new iMacs have a Target Display Mode, but it's built to do that.  Without ripping your screen out, finding an acceptable power supply, frame, and whatever electronics to convert a Thunderbolt signal to the screen, the cost will be much larger than buying a cheaper HiDef monitor that runs with an HDMI to Thunderbolt cable to your MacBook 15.  In fact, you can sell your 17" MBP for a lot of money, unless it's broken or something, buying you a really sweet monitor.
    By the way, I found your answer by searching this forum.  I would suggest using the search function here in the futuere.

  • I had an Apple ID and password with my hotmail acct.  The password stopped working, so I set up a new one with my me acct.  How can I access my old acct. and merge the two of them?

    I had an Apple ID and password with my hotmail acct.  The password stopped working, so I set up a new one with my me acct.  How can I access my old acct. and merge the two of them?

    https://iforgot.apple.com/cgi-bin/WebObjects/DSiForgot.woa/wa/iforgot?language=C A-EN&app_id=2417&newWindow=true&border=false

  • Version 10 doesn't work with a web site I use constantly. How can I download a lower version and have the app appear on my phone?

    Have been using a lower version of firefox on my samsung galaxy phone to access [email protected] for quite some time. Since the upgrade to 10.0, I receive a server error everytime I try to access. Want to download a lower version, but app doesn't appear on my phone. How can I download a lower version and get the app to show up on my phone?

    Mandel is referring to what is called a "User Agent Faker' which tricks the website into thinking it is a different browser or version than it actually is. I sometimes would use this on my iPhone when I wanted to visit the full website of a site I was attempting to go to & it would only take me to the mobile version or state it was only compatible with say Internet Explorer, simply turn it on & select the browser and details you want it to report and it will spoof that browser & you'll be on your way.

  • HT201150 How can I turn off this "feature" and have the power button bring me the shut down / restart / sleep dialog by default again?

    How can I turn off this "feature" and have the power button bring me the shut down / restart / sleep dialog by default again?
    With the position of the power button on the Retina MacBooks, any mistake turns off the screen in the middle of a presentation or any activity using a projector or big screen — a huge waste of time to wake up the display, enter password, have the projector sync back, watch audience disconnecting from what was being discussed, etc.
    This is very annoying, and seems to add to the increasing collection of options Apple decided to make by itself instead of allowing the user to choose.
    Come on Apple guys, I'm using my Mac because I want options and lots of preferences to tweak to my needs.
    If I needed the lobotomized version I'd be using my iPad!
    Any way (official or hack) to change this button back to its proper funcionality?
    Thanks!

    cterra wrote:
    How can I turn off this "feature" and have the power button bring me the shut down / restart / sleep dialog by default again?
    Not what you want, but you can get the shut down / restart / sleep dialog by holding the power button

  • Can I delete a later backup and keep the latest one as to not eat up all my space?

    Can I delete a later backup and keep the latest one as to not eat up all my space?

    Are you talking about Time Machine backups on a Time Capsule?
    It is fine to delete the backup as long as you are sure there is nothing you want.. and do a new clean backup. That will be the least possible space usage for a working backup.. Never delete files out of an existing backup.. it is very hard to manually delete files in the backup.
    We do not recommend it.

  • How can I change my Profile photo or edit the thumbnail?

    QuestionHow can I change my Profile photo or edit the thumbnail?
    AnswerThere are a couple of different ways to change your profile photo or thumbnail image on Tagged.
    Here's a quick How-to video that shows you how to change your profile photo
    If you wish to change your profile photo, follow the instructions listed below:
    Hover your mouse over 'More' in the top Nav bar and select Photos.
    To use one of your previously uploaded photos as your profile photo, place the cursor over the photo you wish to use, and click the small green “#1” box when it appears
    If you wish to use a new image as your profile photo, upload the image to your photo gallery, and then click the small green “#1” box on the photo
    If you are viewing one of your photos individually, you can also set it as your profile photo by hovering over it and clicking the same green "#1" button.  You may also edit the caption and comment on your photo in this view
    You can also change your profile photo by doing the following:
    On the Navigation bar click Profile and select the Edit Profile link to the left of your Profile picture.
    To upload a photo locally from your computer, click the “Browse” button, select the image you wish you use, and then click “Upload”.
    To upload a photo using an image URL address, click the “Add from image URL” link, paste the URL address into the field, and click “Add Photo”.
    To use a photo from your gallery, click the “Use one of my photos” link to open a thumbnail gallery of your uploaded images.  Click on a thumbnail to set that image as your profile photo.
    After selecting a photo, you can alter its thumbnail by the marquee box by dragging the “anchor” points of the box.  When you are finished, click "Save Thumbnail"

    HELP! I was fooling around with my profile pic and selected and saved a cropped thumbnail. I hate it, and I haven't been able to figure out how to return my thumbnail to just a mini-version of my full profile pic. I've even re-up-loaded a copy of the original photo, with a different file name, but Tagged automatically crops it to the same thumbnail.  Is there any way to return my thumbnail to just a mini-version of my whole pic?  Thanks for your help :~)  

  • Every time I hit the app store I get the message "loading".   How can I get out of this and get the app "qrreader" that I want to load???

    I'm getting a little frustrated trying to get the "APP "  "qrreader".  Everytime I tap on the APP icon it is "loading".  How can I get out of this and start over with the
    APP I want???

    Try a reset: hold down the home button along with the power button until you see the Apple, then let go.

  • How do I convert .txt to .pdf and keep the formatting

    I have a large .txt file that I would like to convert to .pdf.  I have tried to print the file and choose Adobe PDF but the output is just a mess.  I loose all the formatting and get blank pages every so often.  Does anyone know if is possible to convert .txt to .pdf and keep the formatting.  I would try a virtual printer application but I am not able to just install any application on my office computer.  Any help would be greatly appreciated.

    It may be a bit late for you now but in future (and for anyone else interested) I would recommend copying the text into a word document and changing the text font to Consolas. Adjust the size to fit the page again and it should match the original notepad formatting.

  • How can I customise layout of photos and text PhotoBooks in Photos

    I started a PhotoBook in iPhoto on Maverick. Before it was finished I upgraded to Yosemite and found that iPhotos has been replaced by Photos. When I tried to continue editing ie enlarge my text box or make a photo from landscape to portrait, it does not accept "Command + Option + arrow. As I am in the middle of creating the book, I am in a bit of trouble. Can anyone give me new commands that work in "Photo"?
    Annie.e

    Have you tried using iPhoto and the iPhoto Library?  You will need iPhoto 9.6.1 but if you had any version of iPhoto 9 at the time of upgrade you may be able to go to the App Store and download iPhoto 9.6.1. 
    You've learned one of the age old adages of computing: Never upgrade before finishing a project.
    One method of customizing a page in a photo book is to create the page in Pages in the landscape orientation for US letter - borderless.  When done do a Print ➙ Save as PDF of the one page.  In Preview select  the one page and export as a jpeg.  Add that jpeg file to Photos add to the Book and use in this layout:
    which is using the photo for the page's background. 
    A tutorial on how another method to customize a page (but for iPhoto) is: iP11 - Creating a Custom Page, with the Theme's Background for an iPhoto Book.  Some of the elements can be used for Photos.  I'm working on a tutorial for Photos but it won't be ready for a while yet.

Maybe you are looking for

  • Cannot install Photoshop CS4 on Windows Vista Business

    Ok people, looking for some help with this.  I have a new PC (less than 2 months old).  I cannot get Photoshop CS4 installed at all.  I'm sure there have been a million threads like this before asking the same question.  Although I am a newb to Photo

  • Poor performance of BLOB queries using ODBC

    I'm getting very poor performance when querying a BLOB column using ODBC. I'm using an Oracle 10g database and the Oracle 10g ODBC driver on Windows XP. I create two tables: create table t1 ( x int primary key, y raw(2000) ); create table t2 ( x int

  • How to get KM Layout Set Description

    Hello, Can we get the Layout Set description through KM API? We are able to get all existing Layout sets using String[] ids=layoutService.getAllLayoutSetIDs(); but we want descriptions also for these Layout Sets Please let me know if anybody have an

  • App Store Reviews

    Is there anything I might be doing wrong? I've now tried writing app reviews for about 10 apps over the last year and NEVER have I seen it in the reviews? Do all reviews get published and if so are they instantly or do apple check them first? My revi

  • How to disable a field on the basis radio button value selected.

    hello to all, i am facing one problem.I have declared two selection screen blocks. In one i hvae declared two radio button r1 -Fiscal year and r2--Datewise. And in another selection screen block all i/p fields. like plant. date.year etc. Now if user