简体   繁体   中英

Transparent PNG is showing black backround in Canvas Java

I have a code which choose a PNG image and shows it in a canvas as a background image:

    import java.util.ArrayList;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

import tr.bm.color.Palette;
import and.graphics.Bitmap;

import com.basari.dao.ContentAndDAO;
import com.basari.entity.ContentAnd;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.graphics.Point;


public class ColorDraw 
{
    protected Shell shlDrawPalette;
    private Text txtPushCode;
    private Text txtUrl;
    private static ContentAndDAO dao = new ContentAndDAO();
    private Button btnDraw;
    private static final int IMG_WIDTH = 100;
    private static final int IMG_HEIGHT = 100;

    public static void main(String[] args) 
    {   
        try 
        {
            ColorDraw window = new ColorDraw();
            window.open();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }

    public void open() {
        Display display = Display.getDefault();
        createContents();
        shlDrawPalette.open();
        shlDrawPalette.layout();
        while (!shlDrawPalette.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }
    }

    protected void createContents() {
        shlDrawPalette = new Shell();
        shlDrawPalette.setMinimumSize(new Point(38, 35));
        shlDrawPalette.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
        shlDrawPalette.setSize(729, 649);
        shlDrawPalette.setText("Draw Palette");
        shlDrawPalette.setLayout(new FormLayout());

        txtPushCode = new Text(shlDrawPalette, SWT.BORDER);
        FormData fd_txtPushCode = new FormData();
        fd_txtPushCode.top = new FormAttachment(0, 18);
        fd_txtPushCode.left = new FormAttachment(0, 94);
        txtPushCode.setLayoutData(fd_txtPushCode);

        txtUrl = new Text(shlDrawPalette, SWT.BORDER);
        FormData fd_txtUrl = new FormData();
        fd_txtUrl.right = new FormAttachment(0, 519);
        fd_txtUrl.top = new FormAttachment(0, 70);
        fd_txtUrl.left = new FormAttachment(0, 94);
        txtUrl.setLayoutData(fd_txtUrl);

        Button btnOk = new Button(shlDrawPalette, SWT.NONE);
        FormData fd_btnOk = new FormData();
        fd_btnOk.right = new FormAttachment(0, 184);
        fd_btnOk.top = new FormAttachment(0, 117);
        fd_btnOk.left = new FormAttachment(0, 94);
        btnOk.setLayoutData(fd_btnOk);
        btnOk.addSelectionListener(new SelectionAdapter() 
        {
            @Override
            public void widgetSelected(SelectionEvent e) 
            {                           
                try
                {
                    if(txtUrl.getText() == "")
                    {
                        Long pushCode = Long.valueOf(txtPushCode.getText());
                        ContentAnd content = dao.getContentAnd(pushCode);
                        downloadIconPushCode(content);
                    }

                    if(txtPushCode.getText() == "")
                    {                           
                        downloadIconUrl(txtUrl.getText());  
                    }
                }
                catch(Exception ex)
                {
                    String pushCode = txtPushCode.getText();
                    writeFileNotFound(pushCode);
                    JOptionPane.showMessageDialog(null, "BÖYLE BİR PUSHCODE YOK, TEKRAR DENEYİN");
                    ex.getStackTrace();
                }
            }
        });
        btnOk.setText("OK");    

        Label lblPushcode = new Label(shlDrawPalette, SWT.NONE);
        FormData fd_lblPushcode = new FormData();
        fd_lblPushcode.right = new FormAttachment(0, 80);
        fd_lblPushcode.top = new FormAttachment(0, 18);
        fd_lblPushcode.left = new FormAttachment(0, 10);
        lblPushcode.setLayoutData(fd_lblPushcode);
        lblPushcode.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
        lblPushcode.setText("PushCode");

        Label lblUrl = new Label(shlDrawPalette, SWT.NONE);
        FormData fd_lblUrl = new FormData();
        fd_lblUrl.right = new FormAttachment(0, 80);
        fd_lblUrl.top = new FormAttachment(0, 70);
        fd_lblUrl.left = new FormAttachment(0, 10);
        lblUrl.setLayoutData(fd_lblUrl);
        lblUrl.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
        lblUrl.setText("URL");

        Canvas canvBackgroundLightVibrant = new Canvas(shlDrawPalette, SWT.NONE);
        FormData fd_canvBackgroundLightVibrant = new FormData();
        fd_canvBackgroundLightVibrant.left = new FormAttachment(0, 208);
        canvBackgroundLightVibrant.setLayoutData(fd_canvBackgroundLightVibrant);

        Canvas canvIconLightVibrant = new Canvas(canvBackgroundLightVibrant, SWT.NONE);
        canvIconLightVibrant.setBounds(38, 35, 89, 100);

        Canvas canvBackgroundDarkVibrant = new Canvas(shlDrawPalette, SWT.NONE);
        fd_canvBackgroundLightVibrant.right = new FormAttachment(canvBackgroundDarkVibrant, -1);
        FormData fd_canvBackgroundDarkVibrant = new FormData();
        fd_canvBackgroundDarkVibrant.top = new FormAttachment(txtUrl, 114);
        fd_canvBackgroundDarkVibrant.left = new FormAttachment(0, 370);
        fd_canvBackgroundDarkVibrant.right = new FormAttachment(100, -164);
        canvBackgroundDarkVibrant.setLayoutData(fd_canvBackgroundDarkVibrant);

        Canvas canvIconDarkVibrant = new Canvas(canvBackgroundDarkVibrant, SWT.NONE);
        canvIconDarkVibrant.setBounds(38, 35, 89, 100);

        Canvas canvBackgroundMuted = new Canvas(shlDrawPalette, SWT.NONE);
        FormData fd_canvBackgroundMuted = new FormData();
        fd_canvBackgroundMuted.bottom = new FormAttachment(0, 564);
        fd_canvBackgroundMuted.right = new FormAttachment(0, 206);
        fd_canvBackgroundMuted.top = new FormAttachment(0, 392);
        fd_canvBackgroundMuted.left = new FormAttachment(0, 45);
        canvBackgroundMuted.setLayoutData(fd_canvBackgroundMuted);

        Canvas canvIconMuted = new Canvas(canvBackgroundMuted, SWT.NONE);
        canvIconMuted.setBounds(38, 35, 89, 100);

        Canvas canvBackgroundLightMuted = new Canvas(shlDrawPalette, SWT.NONE);
        fd_canvBackgroundLightVibrant.bottom = new FormAttachment(canvBackgroundLightMuted, -1);
        FormData fd_canvBackgroundLightMuted = new FormData();
        fd_canvBackgroundLightMuted.top = new FormAttachment(0, 392);
        fd_canvBackgroundLightMuted.bottom = new FormAttachment(canvBackgroundMuted, 0, SWT.BOTTOM);
        fd_canvBackgroundLightMuted.right = new FormAttachment(canvBackgroundLightVibrant, 0, SWT.RIGHT);
        fd_canvBackgroundLightMuted.left = new FormAttachment(0, 208);
        canvBackgroundLightMuted.setLayoutData(fd_canvBackgroundLightMuted);

        Canvas canvIconLightMuted = new Canvas(canvBackgroundLightMuted, SWT.NONE);
        canvIconLightMuted.setBounds(38, 35, 89, 100);

        Label lblLightMuted = new Label(canvBackgroundLightMuted, SWT.NONE);
        lblLightMuted.setBounds(38, 0, 88, 20);
        lblLightMuted.setText("Light Muted");

        Canvas canvBackgroundDarkMuted = new Canvas(shlDrawPalette, SWT.NONE);
        fd_canvBackgroundDarkVibrant.bottom = new FormAttachment(canvBackgroundDarkMuted, -1);
        FormData fd_canvBackgroundDarkMuted = new FormData();
        fd_canvBackgroundDarkMuted.top = new FormAttachment(canvBackgroundMuted, 0, SWT.TOP);

        Label lblMuted = new Label(canvBackgroundMuted, SWT.NONE);
        lblMuted.setBounds(38, 0, 70, 20);
        lblMuted.setText("Muted");
        fd_canvBackgroundDarkMuted.left = new FormAttachment(canvBackgroundDarkVibrant, 0, SWT.LEFT);

        Label lblDarkVibrant = new Label(canvBackgroundDarkVibrant, SWT.NONE);
        lblDarkVibrant.setBounds(38, 0, 99, 20);
        lblDarkVibrant.setText("Dark Vibrant");
        fd_canvBackgroundDarkMuted.bottom = new FormAttachment(0, 564);
        fd_canvBackgroundDarkMuted.right = new FormAttachment(0, 547);
        canvBackgroundDarkMuted.setLayoutData(fd_canvBackgroundDarkMuted);

        Canvas canvIconDarkMuted = new Canvas(canvBackgroundDarkMuted, SWT.NONE);
        canvIconDarkMuted.setBounds(43, 35, 89, 100);

        Label lblDarkMuted = new Label(canvBackgroundDarkMuted, SWT.NONE);
        lblDarkMuted.setBounds(43, 0, 90, 20);
        lblDarkMuted.setText("Dark Muted");

        btnDraw = new Button(shlDrawPalette, SWT.NONE);
        fd_canvBackgroundLightVibrant.top = new FormAttachment(btnDraw, 63);

        Label lblLightVibrant = new Label(canvBackgroundLightVibrant, SWT.NONE);
        lblLightVibrant.setBounds(38, 0, 93, 20);
        lblLightVibrant.setText("Light Vibrant");

        Canvas canvBackgroundVibrant = new Canvas(shlDrawPalette, SWT.NONE);
        FormData fd_canvBackgroundVibrant = new FormData();
        fd_canvBackgroundVibrant.bottom = new FormAttachment(canvBackgroundLightVibrant, 0, SWT.BOTTOM);
        fd_canvBackgroundVibrant.right = new FormAttachment(canvBackgroundMuted, 0, SWT.RIGHT);
        fd_canvBackgroundVibrant.top = new FormAttachment(canvBackgroundLightVibrant, 0, SWT.TOP);
        fd_canvBackgroundVibrant.left = new FormAttachment(canvBackgroundMuted, 0, SWT.LEFT);
        canvBackgroundVibrant.setLayoutData(fd_canvBackgroundVibrant);

        Canvas canvIconVibrant = new Canvas(canvBackgroundVibrant, SWT.NONE);
        canvIconVibrant.setBounds(38, 35, 89, 100);

        Label lblVibrant = new Label(canvBackgroundVibrant, SWT.NONE);
        lblVibrant.setBounds(37, 0, 70, 20);
        lblVibrant.setText("Vibrant");

        FormData fd_btnDraw = new FormData();
        fd_btnDraw.right = new FormAttachment(0, 300);
        fd_btnDraw.top = new FormAttachment(0, 117);
        fd_btnDraw.left = new FormAttachment(0, 210);
        btnDraw.setLayoutData(fd_btnDraw);
        btnDraw.addSelectionListener(new SelectionAdapter() 
        {
            @Override
            public void widgetSelected(SelectionEvent e) 
            {
                try
                {
                    JFrame parentFrame = new JFrame();
                    JFileChooser fileChooser = new JFileChooser();

                    fileChooser.setDialogTitle(txtUrl.getText());   

                    int userSelection = fileChooser.showOpenDialog(parentFrame);

                    if (userSelection == JFileChooser.APPROVE_OPTION) 
                    {       
                        ArrayList<String> colorList = new ArrayList<String>();
                        File fileToSave = fileChooser.getSelectedFile();
                        String fileName = fileToSave.getAbsolutePath();
                        BufferedImage image = null;
                        image = ImageIO.read(new File(fileName));   

                        int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
                        BufferedImage resizeImageHintPng = resizeImageWithHint(image, type);
                        ImageIO.write(resizeImageHintPng, "png", new File(fileName)); 

                        Bitmap bitmap = new Bitmap(image);
                        Palette palette = Palette.generate(bitmap);

                        int vibrant = palette.getVibrantColor(0xFFFFFF);
                        int vibrantLight = palette.getLightVibrantColor(0xFFFFFF);
                        int vibrantDark = palette.getDarkVibrantColor(0xFFFFFF);
                        int muted = palette.getMutedColor(0xFFFFFF);
                        int mutedLight = palette.getLightMutedColor(0xFFFFFF);
                        int mutedDark = palette.getDarkMutedColor(0xFFFFFF);

                        String hexColor = String.format("#%06X", (0xFFFFFF & vibrant)); 
                        colorList.add(hexColor);
                        canvBackgroundVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2))); 
                        canvIconVibrant.setBackgroundImage(SWTResourceManager.getImage(fileName));  
                        canvIconVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));                       
                        lblVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

                        hexColor = String.format("#%06X", (0xFFFFFF & vibrantLight));   
                        colorList.add(hexColor);
                        canvBackgroundLightVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));
                        canvIconLightVibrant.setBackgroundImage(SWTResourceManager.getImage(fileName));                     
                        lblLightVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

                        hexColor = String.format("#%06X", (0xFFFFFF & vibrantDark));        
                        colorList.add(hexColor);
                        canvBackgroundDarkVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));
                        canvIconDarkVibrant.setBackgroundImage(SWTResourceManager.getImage(fileName));
                        lblDarkVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

                        hexColor = String.format("#%06X", (0xFFFFFF & muted));  
                        colorList.add(hexColor);
                        canvBackgroundMuted.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));
                        canvIconMuted.setBackgroundImage(SWTResourceManager.getImage(fileName));
                        lblMuted.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

                        hexColor = String.format("#%06X", (0xFFFFFF & mutedLight)); 
                        colorList.add(hexColor);
                        canvBackgroundLightMuted.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));
                        canvIconLightMuted.setBackgroundImage(SWTResourceManager.getImage(fileName));
                        lblLightMuted.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

                        hexColor = String.format("#%06X", (0xFFFFFF & mutedDark));      
                        colorList.add(hexColor);
                        canvBackgroundDarkMuted.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));
                        canvIconDarkMuted.setBackgroundImage(SWTResourceManager.getImage(fileName));
                        lblDarkMuted.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

                        //drawPalet(fileName, colorList);                       
                        System.out.println("colorList: " + colorList);
                        JOptionPane.showMessageDialog(null, "DRAWING IS FINISHED");
                    }
                }
                catch(Exception ex)
                {
                    System.out.println("CAN'T DRAW!");
                    ex.getMessage();
                }
            }
        });
        btnDraw.setText("Draw");        
    }

    public static void drawPalet(String fileName, ArrayList<String> colorList) 
    {       
        BufferedImage b_img = new BufferedImage(500, 100, BufferedImage.TYPE_INT_ARGB);
        Graphics2D graphics = b_img.createGraphics();
        int i=0;
        for(String color:colorList)
        {
            java.awt.Color colorAwt = new java.awt.Color(hex2Rgb(color, 0), hex2Rgb(color, 1), hex2Rgb(color, 2));
            System.out.println("hex color: " + color);
            graphics.setColor(colorAwt);
            graphics.fillRect(i, 0, 100, 100);
            i=+100;
            System.out.println("colorAwt: " + colorAwt);
        }

        File outputfile = new File(fileName + "_drawed.jpg");
        try 
        {
            ImageIO.write(b_img, "jpg", outputfile);
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }       
    }


    public static int hex2Rgb(String colorStr, int val) {

        if(val == 0)
            return (Integer.valueOf(colorStr.substring(1, 3), 16));
        else if (val == 1)
            return Integer.valueOf(colorStr.substring(3, 5), 16);
        else if(val == 2)
            return Integer.valueOf(colorStr.substring(5, 7), 16);
        else
            return 0;
    }

    private static BufferedImage resizeImageWithHint(BufferedImage originalImage, int type)
    {        
        BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
        g.dispose();    
        g.setComposite(AlphaComposite.Src);

        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g.setRenderingHint(RenderingHints.KEY_RENDERING,
                RenderingHints.VALUE_RENDER_QUALITY);
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        return resizedImage;
    }   

    public boolean downloadIconUrl(String url) 
    {
        try 
        {
            JFrame parentFrame = new JFrame();
            JFileChooser fileChooser = new JFileChooser();

            fileChooser.setDialogTitle(txtUrl.getText());   

            int userSelection = fileChooser.showSaveDialog(parentFrame);

            if (userSelection == JFileChooser.APPROVE_OPTION) 
            {
                File fileToSave = fileChooser.getSelectedFile();
                System.out.println("Downloaded File: " + fileToSave.getAbsolutePath() + ".png");

                String fileName = fileToSave.getAbsolutePath() + ".png";

                URL link = new URL(url); 

                InputStream in = new BufferedInputStream(link.openStream());
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[1024];
                int n = 0;
                while (-1 != (n = in.read(buf))) 
                {
                    out.write(buf, 0, n);
                }
                out.close();
                in.close();
                byte[] response = out.toByteArray();

                FileOutputStream fos = new FileOutputStream(fileName);
                fos.write(response);
                fos.close();

                System.out.println("Image File Downloaded");
            }
        } 
        catch (IOException ex) 
        {
            ex.printStackTrace();
        }

        return true;
    }

PNG image is appearing like this on a canvas:

在此输入图像描述

But as you can see, its an PNG image with transparent background

在此输入图像描述

I searched the internet and found that I must make type of BufferedImage as TYPE_INT_ARGB and I have to use PNG images. And as you can see, my code is like that. What am I doing wrong?

I solved my own problem. I used label in canvas instead of canvas in canvas. And used its setImage and after setBackground methods.

lblIconVibrant.setImage(SWTResourceManager.getImage(fileName);
lblIconVibrant.setBackground(SWTResourceManager.getColor(hex2Rgb(hexColor, 0), hex2Rgb(hexColor, 1), hex2Rgb(hexColor, 2)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM