RGBImageFilter not affecting my image - java

I am trying to change the colors in a .png-file using RGBImageFilter and FilteredImageSource and then save the file to disk, and it seems to be working fine.. but when I open the new file after the program has finished, it looks just like the original, i.e. I have just copied the file.
The codes looks like this:
public class ChangeImageColor {
public static void main(String[] args) {
BufferedImage image = null;
try {
image = ImageIO.read(new File("png_test.png") );
ImageFilter colorfilter = new RedBlueSwapFilter();
FilteredImageSource filteredImageSource = new FilteredImageSource(image.getSource(), colorfilter );
Image filteredImage = Toolkit.getDefaultToolkit().createImage(filteredImageSource);
BufferedImage filtered = new BufferedImage(
filteredImage.getWidth(null), filteredImage.getHeight(null),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = filtered.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
save(filtered, "png");
} catch( IOException e){
//do something
System.out.print(e.getMessage());
}
}
private static void save(BufferedImage image, String ext) {
String fileName = "png_test_manipulated";
File file = new File(fileName + "." + ext);
try {
ImageIO.write(image, ext, file); // ignore returned boolean
} catch(IOException e) {
System.out.println("Write error for " + file.getPath() +
": " + e.getMessage());
}
}
static class RedBlueSwapFilter extends RGBImageFilter {
public RedBlueSwapFilter() {
// The filter's operation does not depend on the
// pixel's location, so IndexColorModels can be
// filtered directly.
canFilterIndexColorModel = true;
}
#Override
public int filterRGB(int x, int y, int rgb) {
/*return ((rgb & 0xff00ff00)
| ((rgb & 0xff0000) >> 16)
| ((rgb & 0xff) << 16));*/
return 0x00000000;
}
}
}

your problem:
g2.drawImage(image, 0, 0, null);
you draw the old image with this code, try to remove this lines:
Graphics2D g2 = filtered.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();

Related

Problems with getting back rotated images from HashMap

I have the following problems:
I don't know why my function, when displaying already rotated images, shows only one in as many jpanels as there were photos given.
Let me give an example: I load 4 images into hashmap. Then I put them into my rotate function and try to display them. I end up with 4 tabs of one rotated image.
When I'm trying to rotate twice using the same deegres as used previously (I'm using slider to take degrees) it doesn't rotate anymore but if I touch slider and move it, the function rotates normally.
I had no idea how to convert an Image type into File object thus I converted it into BufferedImage and then to File. I browsed through the Internet but could not find anything helpful.
My main's class piece of code:
JPanel panel_2e = new JPanel();
panel_2e.setOpaque(true);
panel_2e.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED, Color.GRAY, Color.DARK_GRAY), "Rotate options"));
panel_2e.setLayout(new BoxLayout(panel_2e,BoxLayout.Y_AXIS));
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 360, 180);
slider.setMinorTickSpacing(10);
slider.setMajorTickSpacing(90);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
slider.setLabelTable(slider.createStandardLabels(45));
JPanel radio_buttons_rotate=new JPanel();
radio_buttons_rotate.setLayout(new BoxLayout(radio_buttons_rotate, BoxLayout.Y_AXIS));
JCheckBox cut_frame = new JCheckBox("Cut edges");
cut_frame.setSelected(true);
cut_frame.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED)
{check = true;
System.out.println("Cut-edge mode selected");}
else
{check = false;
System.out.println("Cut-edge mode deselected");}
}
});
cut_frame.setBounds(78, 41, 60, 23);
radio_buttons_rotate.add(cut_frame);
JRadioButton black_rdbutton = new JRadioButton("Black background");
black_rdbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
black = true;
}
});
black_rdbutton.setBounds(78, 41, 60, 23);
radio_buttons_rotate.add(black_rdbutton);
JRadioButton white_rdbutton = new JRadioButton("White background");
white_rdbutton.setSelected(true);
white_rdbutton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
black = false;
}
});
white_rdbutton.setBounds(78, 41, 60, 23);
radio_buttons_rotate.add(white_rdbutton);
ButtonGroup group_frame_rotate = new ButtonGroup();
group_frame_rotate.add(black_rdbutton);
group_frame_rotate.add(white_rdbutton);
panel_2e.add(radio_buttons_rotate);
JLabel Rotate = new JLabel();
Rotate.setText(deg+"\u00b0");
panel_2e.add(slider);
JButton btnRotate = new JButton("Rotate");
JPanel RotatePanel=new JPanel();
RotatePanel.add(Rotate);
RotatePanel.add(btnRotate);
RotatePanel.setLayout(new FlowLayout());
btnRotate.setBounds(28, 158, 89, 23);
btnRotate.setBackground(Color.DARK_GRAY);
btnRotate.setForeground(Color.WHITE);
panel_2e.add(RotatePanel);
panel_2.add(panel_2e);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
deg=((JSlider) ce.getSource()).getValue();
Rotate.setText(deg+"\u00b0"); }
});
btnRotate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(AddDirectory.all_chosen.isEmpty())
{Object[] options = {"OK"};
int n = JOptionPane.showOptionDialog(frame,
"Please choose at least 1 image to rotate.","Empty work list",
JOptionPane.PLAIN_MESSAGE,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);}
else
{RotateFunction rot = new RotateFunction(AddDirectory.all_chosen);
rot.main();
BufferedImage kk = null;
Display disp= new Display(); // invoke Display class
for(File i : all_chosen_images.values()){
try{
kk = ImageIO.read(new File(i.getAbsolutePath()));
disp.createFrame(center, i, kk); //create new frame with image
}
catch (IOException es){
es.printStackTrace();
}
}
}
}
});
And here is my rotate function:
public class RotateFunction{
HashMap<JButton,File> map;
Image spiral;
RotateFunction(HashMap<JButton,File> source_of_image)
{
map = AddDirectory.all_chosen;
}
public void main(){
int counter = 0;
if (spiral == null){
for(Map.Entry<JButton, File> entry: map.entrySet()) //////Moving through hashMap
{
try {
spiral = getImage(entry.getValue().getAbsolutePath());
counter++;
System.out.println("Path of image " + counter + " : " +entry.getValue().getAbsolutePath());
if (PhotoEdit.check == true){
rotateImage(PhotoEdit.deg, null);
System.out.println("Rotating image "+counter+" by "+PhotoEdit.deg+" degrees (edge cut)");
}
else{
rotateImage1(PhotoEdit.deg, null);
System.out.println("Rotating image "+counter+" by "+PhotoEdit.deg+" degrees (bigger frame)");
}
BufferedImage tmp = toBufferedImage(spiral);
File f;
f = new File( "image.png" );
try
{
ImageIO.write( tmp, "PNG", f );
}
catch ( IOException x )
{
// Complain if there was any problem writing
// the output file.
x.printStackTrace();
}
map.put(entry.getKey(), f);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PhotoEdit.all_chosen_images.clear();
PhotoEdit.all_chosen_images.putAll(map); //Putting HashMap with rotated images into global HashMap
System.out.println("Images have been successfully rotated");
}
}
public Image getImage(String path){
Image tempImage = null;
try
{
tempImage = Toolkit.getDefaultToolkit().getImage(path);
}
catch (Exception e)
{
System.out.println("An error occured - " + e.getMessage());
}
return tempImage;
}
////////////////////////////////////////////////////////////////////
///////////////////IMAGE ROTATION /////////////////////////////////
public void rotateImage(double degrees, ImageObserver o){
ImageIcon icon = new ImageIcon(this.spiral);
BufferedImage blankCanvas = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)blankCanvas.getGraphics();
g2.rotate(Math.toRadians(degrees), icon.getIconWidth()/2, icon.getIconHeight()/2);
g2.drawImage(this.spiral, 0, 0, o);
this.spiral = blankCanvas;
}
public void rotateImage1(double degrees, ImageObserver o){
double sin = Math.abs(Math.sin(Math.toRadians(degrees)));
double cos = Math.abs(Math.cos(Math.toRadians(degrees)));
ImageIcon icon = new ImageIcon(this.spiral);
int w = icon.getIconWidth();
int h = icon.getIconHeight();
int neww = (int)Math.floor(w*cos+h*sin);
int newh = (int)Math.floor(h*cos+w*sin);
BufferedImage blankCanvas = new BufferedImage(neww, newh, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = (Graphics2D)blankCanvas.getGraphics();
g2.translate((neww-w)/2, (newh-h)/2);
g2.rotate(Math.toRadians(degrees), icon.getIconWidth()/2, icon.getIconHeight()/2);
g2.drawImage(this.spiral, 0, 0, o);
this.spiral = blankCanvas;
}
//////////////////////////////////////////////////////////////////////////
public static BufferedImage toBufferedImage(Image img)
{
if (img instanceof BufferedImage)
{
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
// Draw the image on to the buffered image
Graphics2D bGr = bimage.createGraphics();
bGr.drawImage(img, 0, 0, null);
bGr.dispose();
// Return the buffered image
return bimage;
}
}
In the display function i have the following arguments - createFrame(JDekstopPane where_to_put_the_image, File img, BufferedImage image)
HashMap - all_chosen_images is the global HashMap storing all the images
Really hope for your help.
Aleksander

RGB value not change correctly after saving image in JAVA

I'm trying to read an Image type JPG/JPEG to BufferedImage , change RGB value of pixel (0,0)
Image file : http://i.upanh.com/rcfutp
but it didn't work correctly
Here is what i've try
Read image
public BufferedImage readImage1(String path)
{
BufferedImage _image = null;
BufferedImage copy = null;
try {
_image = ImageIO.read(new File(path));
copy = new BufferedImage(_image.getWidth(), _image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
copy.getGraphics().drawImage(_image, 0, 0, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return copy;
}
Write Image
public void writeImage1(String path,BufferedImage _image)
{
try {
ImageIO.write(_image, "jpg", new File(path));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Client Code
BufferedImage image = readImage1("E:/2.jpg");
System.out.print((image.getRGB(0, 0))&0xFFFFFF);
System.out.print("-");
image.setRGB(0, 0, 0x00000F);
System.out.print((image.getRGB(0, 0))&0xFFFFFF);
System.out.print("-");
writeImage1("E:/3.jpg", image);
image = readImage1("E:/3.jpg");
System.out.print((image.getRGB(0, 0))&0xFFFFFF);
System.out.print return
7736127-15-5439516
I hope it was 7736127-15-15,but it return 7736127-15-5439516
please help me to correct ,thank you very much guy
This is not possible because of how jpg compresses data, when you are operating on every pixel of the image it is the unpacked version of the image you are operating on, the jpg format is a lossy compression format. Compressing an image then decompressing it will not yield the original image. This is why pixel values are different.
This can be clearly seen in the following image. Notice the "lines" to the right, the right side is the jpg compression then decompression of the left side.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.beans.Transient;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class ImageTest extends JPanel {
private BufferedImage image;
private BufferedImage saved;
public ImageTest(int w, int h) {
image = new BufferedImage(w, h, BufferedImage.TYPE_3BYTE_BGR);
randomizeImage(image);
saveAndLoadImage();
saveResultToLossLess();
}
private void saveResultToLossLess() {
BufferedImage result = new BufferedImage(image.getWidth() * 2,
image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
result.getGraphics().drawImage(image, 0, 0, null);
result.getGraphics().drawImage(saved, image.getWidth(), 0, null);
try {
ImageIO.write(result, "png", new File("comparison.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void randomizeImage(BufferedImage image) {
// Draw a blue gradient, note that in the array below
// pixels[i] = blue, pixels[i+1] = green, pixels[i+2] = red
byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer())
.getData();
for (int i = 0; i < pixels.length; i += 3) {
pixels[i] = (byte) (255.0 * i / pixels.length);
pixels[i + 1] = (byte) (128.0 * i / pixels.length);
pixels[i + 2] = (byte) (64.0 * i / pixels.length);
}
}
private void saveAndLoadImage() {
try {
ImageIO.write(image, "jpg", new File("image.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
saved = ImageIO.read(new File("image.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
if (saved != null)
g.drawImage(saved, image.getWidth(), 0, null);
}
#Override
#Transient
public Dimension getPreferredSize() {
return new Dimension(image.getWidth() * 2, image.getHeight());
}
public static void main(String[] args) {
ImageTest test = new ImageTest(600, 600);
JFrame frame = new JFrame();
frame.getContentPane().add(test);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}

How to make drawn images transparent in Java

I got the animation to work in my Snake Clone Game. But the problem based on the picture is that the images do not have transparency(notice the white background of the circle pictures. Programming-wise, is there a fix to be able to include transparency to these drawn images?
Here's a picture containing my code and the output of the program.
P.S. On a side note, I decided to paste the direct link instead of the IMG code because I cannot seem to get it to display on StackOverFlow. I put an exclamation point in the front of the IMG code but it did not work so here's the direct link.
As the other answer mentioned, the easiest way would probably be to simply use PNG images which have a transparent background (you can create these with an image editor like GIMP). Alternatively, if you are limited to PNG images with a solid background, here's an example of how to change a given color (e.g. white) in the PNG to transparent:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class SimpleFrame extends JFrame {
JPanel mainPanel = new JPanel() {
ImageIcon originalIcon = new ImageIcon("~/Pictures/apple.png");
ImageFilter filter = new RGBImageFilter() {
int transparentColor = Color.white.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ((rgb | 0xFF000000) == transparentColor) {
return 0x00FFFFFF & rgb;
} else {
return rgb;
}
}
};
ImageProducer filteredImgProd = new FilteredImageSource(originalIcon.getImage().getSource(), filter);
Image transparentImg = Toolkit.getDefaultToolkit().createImage(filteredImgProd);
public void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRect(0, 0, getSize().width, getSize().height);
// draw the original icon
g.drawImage(originalIcon.getImage(), 100, 10, this);
// draw the transparent icon
g.drawImage(transparentImg, 140, 10, this);
}
};
public SimpleFrame() {
super("Transparency Example");
JPanel content = (JPanel)getContentPane();
mainPanel.setBackground(Color.black);
content.add("Center", mainPanel);
}
public static void main(String[] argv) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
SimpleFrame c = new SimpleFrame();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setSize(280,100);
c.setVisible(true);
}
});
}
}
Don't use paint to draw your images. Use some other program that uses alpha like Paint.net or Photoshop... If your going to use circles forever then you can use g.drawOval(x, y, w, h).
Simple use type to ARGB like this
BufferedImage image = new BufferedImage(
width, height,
BufferedImage.TYPE_INT_ARGB);
I hope it should work.
public BufferedImage makeTransparentImage(BufferedImage br) {
for (int i = 0; i < br.getHeight(); i++) {
for (int j = 0; j < br.getWidth(); j++) {
Color c = new Color(br.getRGB(j, i));
int r = c.getRed();
int b = c.getBlue();
int g = c.getGreen();
if ((r == 255 && b == 255 && g == 255)) {
System.out.println("r g b " + r + g + b);
br.setRGB(j, i, 0xFF000000);
}
}
}
return br;
}
If you draw a simple picture,
The easiest and fastest way I know...
Draw a picture in Macrosoft PowerPoint and click "Save as Picture" to get a transparent background. Next...
public class Node {
Image nodeImage[] = new Image[3];
public Node() {
try {
String address = "C:\\Users\\Desktop\\practice\\Simulation\\img\\";
nodeImage[0] = ImageIO.read(new File(address + "Node_noVehicle.png"));
nodeImage[1] = ImageIO.read(new File(address + "Node_setVehicle.png"));
nodeImage[2] = ImageIO.read(new File(address + "Node_inVehicle.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2dtemp = (Graphics2D) g.create();
g2dtemp.drawImage(Node.nodeImage[0],(int)x,(int)y,width,height,this);
}
}
Draw a picture in Macrosoft PowerPoint and click "Save as Picture" to get a transparent background.

About convert Image to byte[] and reverse in Java

i have one problem when i convert image to byte[] and reverse:
I have 2 function convert image to byte[] as follow
public byte[] extractBytes2 (String ImageName) throws IOException {
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
WritableRaster raster = bufferedImage .getRaster();
DataBufferByte data = (DataBufferByte) raster.getDataBuffer();
return ( data.getData() );
}
and
public byte[] extractBytes (String ImageName) throws IOException
{
Path path = Paths.get(ImageName);
byte[] data = Files.readAllBytes(path);
return data;
}
I will have byte[] byteArray
byteArray = extractBytes2("image/pikachu.png");
or
byteArray = extractBytes("image/pikachu.png");
when i convert byte[] to Image i use
Graphics g = panelMain.getGraphics();
Graphics2D g2D = (Graphics2D) g;
try {
InputStream in = new ByteArrayInputStream(byteArray);
BufferedImage image = ImageIO.read(in);
g2D.drawImage(image, 0, 0, GiaoDienChinh.this);
g2D.setPaint(Color.BLACK);
panelMain.setOpaque(true);
panelMain.paintComponents(g2D);
}
catch ( Exception e ) {
}
finally {
}
but i only draw with byteArray use function "extractBytes" not with "extractBytes2" !!!
Anyone can explain me how i can draw image with byteArray which got from "extractByte2"?
Thanks for all support!
Let's start with the paint code.
ImageIO.read(in) is expecting a valid image format that one of it's pluggable service provides knows how to read and convert to a BufferedImage.
When you pass the byes from extractBytes, you're simply passing back an array of bytes that represents the actual image file. I'd be the same as saying Image.read(new File("image/pikachu.png"))
However, the data buffer returned from your extractBytes2 is returning a internal representation of the image data, which may not be "readable" by ImageIO.
UPDATED
A BufferedImage is an accessible buffer of image data, essentially
pixels, and their RGB colors. The BufferedImage provides a powerful
way to manipulate the Image data. A BufferedImage object is made up of
two parts a ColorModel object and a Raster object.
Referenced from here
UPDATED
I had this wacky idea on the way home of how to convert a BufferedImage to a byte array...
The basic idea is to use ImageIO.write to write out the BufferedImage to a ByteOutputStream...
public static byte[] extractBytes2(String ImageName) throws IOException {
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
ByteOutputStream bos = null;
try {
bos = new ByteOutputStream();
ImageIO.write(bufferedImage, "png", bos);
} finally {
try {
bos.close();
} catch (Exception e) {
}
}
return bos == null ? null : bos.getBytes();
}
Here's my test...
public class TestByteImage {
public static void main(String[] args) {
new TestByteImage();
}
public static byte[] extractBytes2(String ImageName) throws IOException {
File imgPath = new File(ImageName);
BufferedImage bufferedImage = ImageIO.read(imgPath);
ByteOutputStream bos = null;
try {
bos = new ByteOutputStream();
ImageIO.write(bufferedImage, "png", bos);
} finally {
try {
bos.close();
} catch (Exception e) {
}
}
return bos == null ? null : bos.getBytes();
}
public TestByteImage() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new ImagePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class ImagePane extends JPanel {
private BufferedImage original;
private byte[] byteData;
private BufferedImage fromBytes;
public ImagePane() {
String name = "/path/to/your/image";
try {
original = ImageIO.read(new File(name));
byteData = extractBytes2(name);
} catch (IOException ex) {
ex.printStackTrace();
}
setFont(UIManager.getFont("Label.font").deriveFont(Font.BOLD, 48f));
}
#Override
public Dimension getPreferredSize() {
return original == null ? super.getPreferredSize() : new Dimension(original.getWidth() * 2, original.getHeight());
}
protected void drawText(Graphics2D g2d, String text, int x, int width) {
BufferedImage img = new BufferedImage(width, getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D tmpg = img.createGraphics();
tmpg.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
tmpg.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
tmpg.setFont(g2d.getFont());
tmpg.setColor(Color.RED);
FontMetrics fm = tmpg.getFontMetrics();
int xPos = ((width - fm.stringWidth(text)) / 2);
int yPos = ((getHeight() - fm.getHeight()) / 2) + fm.getAscent();
tmpg.drawString(text, xPos, yPos);
tmpg.dispose();
AffineTransform transform = g2d.getTransform();
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(-10), x + (x + width) / 2, getHeight() / 2));
g2d.drawImage(img, x, 0, this);
g2d.setTransform(transform);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (original != null) {
g.drawImage(original, 0, 0, this);
drawText((Graphics2D) g, "Original", 0, original.getWidth());
}
if (byteData != null && fromBytes == null) {
try {
fromBytes = ImageIO.read(new ByteInputStream(byteData, byteData.length));
} catch (IOException exp) {
exp.printStackTrace();
}
}
if (fromBytes != null) {
g.drawImage(fromBytes, getWidth() - fromBytes.getWidth(), 0, this);
drawText((Graphics2D) g, "From Bytes", getWidth() - fromBytes.getWidth(), fromBytes.getWidth());
}
}
}
}
Use ImageIo to write bufferedImage into ByteArrayOutputStream, then invoke the toByteArray method of the stream.

ImageIcon not loading

So I am trying to make a small game for a project in college. I have an image class that loads the images etc. I know this class works because I tested it all when I made it. But then I decided to use a form maker, in this case WindowsBuilder Pro to make a form that was better then I could code. I am now trying to call a function that in theory will load call the images class and load the image then add that image as an imageicon to a label within a jPanel. But I am getting nothing. Any help?
private void loadres(){
String PROGRAM_DIRECTORY = "E:/WordGame/bin/Images/";
Functions.Resources rs = new Functions.Resources();
rs.loadResources();
Functions.ImageLib iL = rs.getIL();
try {
BGImage = new JLabel(new ImageIcon(iL.mergeImages(iL.getImageArray(0),iL.getImage(PROGRAM_DIRECTORY + "Astroid1Image.png"))));
} catch (IOException e) {
e.printStackTrace();
}
BGImage.revalidate();
BGImage.repaint();
}
And here is the Image functions I am using:
public class ImageLib {
private ArrayList<BufferedImage> BIArray = new ArrayList<BufferedImage>();
public ImageLib(){
}
public BufferedImage getImage(String ref){
BufferedImage Bi = null;
try{
Bi = ImageIO.read(new File(ref));
}catch (Exception e) {
e.printStackTrace();
}
return Bi;
}
public BufferedImage resizeImage(BufferedImage Bi, int nW, int nH){
int w = Bi.getWidth();
int h = Bi.getHeight();
BufferedImage nBi = new BufferedImage(nW, nH, Bi.getType());
Graphics2D g = nBi.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(Bi,0,0,nW,nH,0,0,w,h,null);
g.dispose();
return nBi;
}
public void addToArray(BufferedImage img){
BIArray.add(img);
}
public BufferedImage getImageArray(int index){
return (BufferedImage) BIArray.get(index);
}
public BufferedImage mergeImages(BufferedImage I1, BufferedImage I2) throws IOException{
int w = Math.max(I1.getWidth(), I2.getWidth());
int h = Math.max(I1.getHeight(), I2.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics g = combined.getGraphics();
g.drawImage(I1, 0, 0, null);
g.drawImage(I2, 0, 0, null);
g.dispose();
return combined;
}
}
Here is my answer ^^
ClassLoader cldr = this.getClass().getClassLoader();
java.net.URL imageURL = cldr.getResource("path/to/your/images/picture.gif");
ImageIcon imgIcon = new ImageIcon(imageURL);

Categories