I have a program here in java and MySQL for database. However the problem is: when the data for IMAGE in the SQL is null, the program stops loading picture.
It shows "java.lang.IllegalArgumentException: input == null!". My question is how will I able to set the Icon picture as null and continue.
try{
PreparedStatement ps = conn.prepareStatement(President);
ResultSet rs = ps.executeQuery();
if(rs.next()){
rs.absolute(1);
FirstName1.setText(rs.getString("cFirstname"));
LastName1.setText(rs.getString("CLastname"));
MiddleName1.setText(rs.getString("cmiddlename"));
BufferedImage im1 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image1 = new ImageIcon(im1);
Image img1 = image1.getImage();
Image newImage = img1.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after = new ImageIcon(newImage);
btnPic1.setIcon(after);
btnPic1.setText("");
FirstName1.setVisible(true);
LastName1.setVisible(true);
btnPic1.setVisible(true);
MiddleName1.setVisible(true);
}
In my data the image stored here is null.
if(rs.next()){
rs.absolute(2);
FirstName2.setText(rs.getString("cFirstname"));
LastName2.setText(rs.getString("CLastname"));
MiddleName2.setText(rs.getString("cmiddlename"));
BufferedImage im2 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image2 = new ImageIcon(im2);
Image img2 = image2.getImage();
Image newImage2 = img2.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after2 = new ImageIcon(newImage2);
btnPic2.setIcon(after2);
btnPic2.setText("");
FirstName2.setVisible(true);
LastName2.setVisible(true);
btnPic2.setVisible(true);
MiddleName2.setVisible(true);
}
Then my program doesn't do this and onwards.
if(rs.next()){
rs.absolute(3);
FirstName3.setText(rs.getString("cFirstname"));
LastName3.setText(rs.getString("CLastname"));
MiddleName3.setText(rs.getString("cmiddlename"));
BufferedImage im3 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image3 = new ImageIcon(im3);
Image img3 = image3.getImage();
Image newImage3 = img3.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after3 = new ImageIcon(newImage3);
btnPic3.setIcon(after3);
btnPic3.setText("");
FirstName3.setVisible(true);
LastName3.setVisible(true);
btnPic3.setVisible(true);
MiddleName3.setVisible(true);
}
Which line throws the IllegalArgumentException? Perhaps I'm being over-simplistic, but a simple solution could be that you check for a null image variable immediately before this line, and if the variable is null, don't use it, and skip that line(s). A better solution is to find out why the images are null and to prevent this from happening in the first place.
The result code would be something like this
if(rs.next()){
rs.absolute(2);
FirstName2.setText(rs.getString("cFirstname"));
LastName2.setText(rs.getString("CLastname"));
MiddleName2.setText(rs.getString("cmiddlename"));
if(rs.getBinaryStream("cimage")!=null){
BufferedImage im2 = ImageIO.read(rs.getBinaryStream("cimage"));
ImageIcon image2 = new ImageIcon(im2);
Image img2 = image2.getImage();
Image newImage2 = img2.getScaledInstance(144, 144, Image.SCALE_SMOOTH);
ImageIcon after2 = new ImageIcon(newImage2);
btnPic2.setIcon(after2);
btnPic2.setText("");}
else{
btnPic2.setText("No Picture");
}
FirstName2.setVisible(true);
LastName2.setVisible(true);
btnPic2.setVisible(true);
MiddleName2.setVisible(true);
}
Adding a "if null" statement. Although in this use. I reverse it. Thank you for the comments and answers. I have been able to come up with this solution.
Related
I need help with the com.lowagie.text.pdf.Barcode128 library, since I would like the image that is generated to include the code below the barcode, like this:
enter image description here
This is the actual code:
public String generateBarCode(String codigo){
try{
Barcode128 codeEAN = new Barcode128();
codeEAN.setCodeType(codeEan.CODE128);
codeEAN.setCode(codigo);
codeEAN.setAltText(codigo);
Image pdfImg = codeEAN.createAwtImage(Color.black, Color.white);
BufferedImage = new BufferedImage(pdfImg.getWidth(null), pdfImg.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.drawImage(pdfImg, 0, 0, Color.white, null);
OutputStream os;
...
...
}
}
This way I only manage to generate the barcode image, but the code under the barcode is not displayed.
Thank you very much in advance.
**I'm using the below code to fetch the multiple failure screenshots from the folder to Bugzilla tool, while uploading the pictures in bugzilla, color of the picture is disorted. [enter image description here][1]. Can any one help me to rectify this issue. ? **
try {
BugzillaConnector conn = new BugzillaConnector();
conn.connectTo("bugzilla.com");
LogIn logIn = new LogIn("username", "password");
conn.executeMethod(logIn);
Bug bug = new BugFactory()
.newBug()
.setProduct("SeleniumFramework")
.setComponent("CoreJavaTestNG")
.setVersion("1.0").setPlatform("PC")
.setOperatingSystem("Windows")
.setDescription("Bug posted from Java Source Code")
.setSummary("Bug posted from Java Source Code")
.createBug();
ReportBug report = new ReportBug(bug);
conn.executeMethod(report);
int bugID = report.getID();
System.out.println("Bug posted and its ID is " + bugID);
GetBug get = new GetBug(bugID);
conn.executeMethod(get);
System.out.println(get.getBug().getID());
System.out.println(get.getBug().getSummary());
System.out.println(get.getBug().getProduct());
System.out.println(get.getBug().getComponent());
System.out.println(get.getBug().getVersion());
System.out.println(get.getBug().getPlatform());
System.out.println(get.getBug().getOperatingSystem());
// Passing txtFileFilter to listFiles() method to retrieve only file start with fail files
File[] files = folder.listFiles(txtFileFilter);
int Count = 0;
for (File file : files) {
BufferedImage bImage = ImageIO.read(new File(FilePath + file.getName()));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bImage, "jpg", bos );
byte [] data = bos.toByteArray();
AttachmentFactory attachmentFactory = new AttachmentFactory();
Attachment attachment = attachmentFactory.newAttachment()
. setData(data)
. setMime("image/jpg") //Set the appropriate MIME type for the image format
. setSummary(file.toString()) //Description
. setName(file.toString())//Name of the Screenshot in Bugzilla
. setBugID(bugID)
. createAttachment();
AddAttachment add2 = new AddAttachment(attachment, bugID);
add2.getID();
conn.executeMethod(add2);
Count++;
}
System.out.println(Count + " File Uploded");
}
catch (Exception e) {
e.printStackTrace();
} ```
[1]: https://i.stack.imgur.com/qrIaq.jpg
The pinkish/readish ting your seeing is because the source image contains a alpha channel.
There is a known bug in ImageIO which will include the alpha channel into the output of the JPEG image (or some such thing, you can google it if you're really interested).
The basic solution to your problem is to apply the original image to a BufferedImage using a TYPE_INT_RGB, which will remove the alpha channel, for example see Removing transparency in PNG BufferedImage.
I used the code but am getting blue color background on the image
So, starting with this transparent PNG
And using the below code...
BufferedImage original = ImageIO.read(new File("/Users/shanew/Downloads/transparent.png"));
BufferedImage copy = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = copy.createGraphics();
g2d.setColor(Color.WHITE); // Or what ever fill color you want...
g2d.fillRect(0, 0, copy.getWidth(), copy.getHeight());
g2d.drawImage(original, 0, 0, null);
g2d.dispose();
File dest = new File("Test.jpg");
ImageIO.write(copy, "jpg", dest);
BufferedImage test = ImageIO.read(dest);
JPanel panel = new JPanel();
panel.add(new JLabel(new ImageIcon(original)));
panel.add(new JLabel(new ImageIcon(test)));
JOptionPane.showMessageDialog(null, panel);
I can produce...
If you're still having issues, then you need to do two things:
Update your original question with the code you are using
Provide a sample of the image you are trying to convert
It's not helpful to keep posting code in the comments
Hi Guys I'm having issue in my Image, I just want to resize the image w/ my label. By using the filechooser. Here is the code below.
try {
File file = jfc.getSelectedFile();
java.net.URL url = file.toURL();
BufferedImage imageBuf = null;
BufferedImage imageSize = null;
try {
imageBuf = ImageIO.read(url);
imageSize = (BufferedImage) imageBuf.getScaledInstance(jlbl_image.getWidth(), jlbl_image.getHeight(),Image.SCALE_SMOOTH);
ImageIcon img;
img = new ImageIcon(imageSize);
jlbl_image.setIcon(img);
} catch (IOException ex) {
Logger.getLogger(JFRecordSection.class.getName()).log(Level.SEVERE, null, ex);
}
Here is the error code when I load the image from fileChooser.
sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
The error message is telling you exactly what the problem is: your image is not a BufferedImage, and so it shouldn't be treated as one. Your assumption is incorrect, however. It's not a that the image loaded from the JFileChooser isn't a BufferedImage, rather it's the scaled image returned from the .getScaledInstance(...) that isn't. So instead cast it to the interface type, Image, and you should be able to use it.
I am trying to set information in some txts. My code is good when all columns are full but when a column is null there is a throw exception and code just doesn't run inside the try catch.
I know that the problem is a null column because the column PhotoQ is an optional data information for the user. So a solution, maybe load a defaultPhoto in all user accounts, but will spend store in the database.
Excuse my English I'm new XD.
Example code:
try {
PreparedStatement pstm = conn.prepareStatement(query);
pstm.setInt(1, userid);
pstm.setInt(2, quizzid);
pstm.setInt(3, NumQuest);
ResultSet rs =pstm.executeQuery();
while (rs.next()) {
fileBytes = rs.getBytes("PhotoQ");
ImageIcon image = new ImageIcon(fileBytes);
Image im = image.getImage();
Image myImg = im.getScaledInstance(lblImage.getWidth(), lblImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon newImage = new ImageIcon(myImg);
if (rs.getString("Optionsid").endsWith("1")) {
txtaA.setText(rs.getString("Options"));
txtaQuestion.setText(rs.getString("Question"));
if (rs.getInt("Valid")==1) {
ckbA.setSelected(true);
}
else {
ckbA.setSelected(false);
}
}
}
}
It seems that your question and error are centered around null values for the PhotoQ and/or Optionsid columns. You should be using explicit checks for nulls, for each column. Only if a column be not null should you attempt to use the value.
Something along these lines should give you an idea of how you might handle this:
while (rs.next()) {
fileBytes = rs.getBytes("PhotoQ");
if (fileBytes != null) {
ImageIcon image = new ImageIcon(fileBytes);
Image im = image.getImage();
Image myImg = im.getScaledInstance(lblImage.getWidth(), lblImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon newImage = new ImageIcon(myImg);
}
String optionsId = rs.getString("Optionsid");
if (optionsId != null && optionsId.endsWith("1")) {
txtaA.setText(rs.getString("Options"));
txtaQuestion.setText(rs.getString("Question"));
Integer valid = rs.getInt("Valid");
if (valid != null && valid.intValue() == 1) {
ckbA.setSelected(true);
} else {
ckbA.setSelected(false);
}
}
}
For fix this issue in my app.
I use a wasnull() but this inside a try just for ask if a record come with a null field, I dont know if a try inside a try is properly but know is working!
code:
try {
PreparedStatement pstm = conn.prepareStatement(query1);
pstm.setInt(1, userid);
pstm.setInt(2, quizzid);
pstm.setInt(3, NumQuest);
ResultSet rs =pstm.executeQuery();
try {
//move result set at first row
rs.next();
fileBytes = rs.getBytes("PhotoQ");
//ask if result set contain null field
if (rs.wasNull()) {
// this variable is defined like globlal
nuller=1;
}else {
nuller=0;
}
} catch (Exception f) {
}
//reload resulset for begin again
rs =pstm.executeQuery();
while (rs.next()) {
//here is thi – Tim Biegeleisen idea
if (nuller==0) {
fileBytes = rs.getBytes("PhotoQ");
ImageIcon image = new ImageIcon(fileBytes);
Image im = image.getImage();
Image myImg = im.getScaledInstance(lblImage.getWidth(), lblImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon newImage = new ImageIcon(myImg);
lblImage.setIcon(newImage);
}
//this code only work for a query with one row result. I use while because my
//teacher example is with while. whe I get finish the system will change the code
#StevenCanales,
You were on the right track you can use the wasNull() to check the value of the last column pulled from the result set. However you do not need the additional try / catch. You can do this all streamlined within the while block.
try {
PreparedStatement pstm = conn.prepareStatement(query1);
pstm.setInt(1, userid);
pstm.setInt(2, quizzid);
pstm.setInt(3, NumQuest);
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
fileBytes = rs.getBytes("PhotoQ");
// ask if result set contain null field
if (rs.wasNull()) {
// handle as you wish... throw an exception ?
} else {
ImageIcon image = new ImageIcon(fileBytes);
Image im = image.getImage();
Image myImg = im.getScaledInstance(lblImage.getWidth(), lblImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon newImage = new ImageIcon(myImg);
if (rs.getString("Optionsid").endsWith("1")) {
txtaA.setText(rs.getString("Options"));
txtaQuestion.setText(rs.getString("Question"));
if (rs.getInt("Valid") == 1) {
ckbA.setSelected(true);
} else {
ckbA.setSelected(false);
}
}
}
}
} catch (Exception e) {
//handle exception
}
The while loop will handle walking the result set appropriately. There isn't anything special you need to do to move to the first record or back or forward.
You have to check for null on fileBytes.
fileBytes = rs.getBytes("PhotoQ");
if (fileBytes != null) {
ImageIcon image = new ImageIcon(fileBytes);
Image im = image.getImage();
Image myImg = im.getScaledInstance(lblImage.getWidth(), lblImage.getHeight(), Image.SCALE_SMOOTH);
ImageIcon newImage = new ImageIcon(myImg);
}
Then well you have to do whatever you want with you newImage object.
I'm trying to make a picture fit a JLabel. I wish to reduce the picture dimensions to something more appropriate for my Swing JPanel.
I tried with setPreferredSize but it doesn't work.
I'm wondering if there is a simple way to do it? Should I scale the image for this purpose?
Outline
Here are the steps to follow.
Read the picture as a BufferedImage.
Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
Create an ImageIcon from the resized BufferedImage.
You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.
Read the picture as a BufferedImage
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
Resize the BufferedImage
Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
Image.SCALE_SMOOTH);
Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.
Create an ImageIcon
ImageIcon imageIcon = new ImageIcon(dimg);
You can try it:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Or in one line:
label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));
The execution time is much more faster than File and ImageIO.
I recommend you to compare the two solutions in a loop.
public static void main(String s[])
{
BufferedImage image = null;
try
{
image = ImageIO.read(new File("your image path"));
} catch (Exception e)
{
e.printStackTrace();
}
ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
jLabel1.setIcon(imageIcon);
}
private Image fitimage(Image img , int w , int h)
{
BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = resizedimage.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0,w,h,null);
g2.dispose();
return resizedimage;
}
The best and easy way for image resize using Java Swing is:
jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));
For better display, identify the actual height & width of image and resize based on width/height percentage
i have done the following and it worked perfectly
try {
JFileChooser jfc = new JFileChooser();
jfc.showOpenDialog(null);
File f = jfc.getSelectedFile();
Image bi = ImageIO.read(f);
image1.setText("");
image1.setIcon(new ImageIcon(bi.getScaledInstance(int width, int width, int width)));
} catch (Exception e) {
}
Or u can do it this way. The function u put the below 6 lines will throw an IOException. And will take your JLabel as a parameter.
BufferedImage bi=new BufferedImage(label.width(),label.height(),BufferedImage.TYPE_INT_RGB);
Graphics2D g=bi.createGraphics();
Image img=ImageIO.read(new File("path of your image"));
g.drawImage(img, 0, 0, label.width(), label.height(), null);
g.dispose();
return bi;
public void selectImageAndResize(){
int returnVal = jFileChooser.showOpenDialog(this); //open jfilechooser
if (returnVal == jFileChooser.APPROVE_OPTION) { //select image
File file = jFileChooser.getSelectedFile(); //get the image
BufferedImage bi;
try {
//
//transforms selected file to buffer
//
bi=ImageIO.read(file);
ImageIcon iconimage = new ImageIcon(bi);
//
//get image dimensions
//
BufferedImage bi2 = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
iconimage.paintIcon(null, g, 0,0);
g.dispose();
//
//resize image according to jlabel
//
BufferedImage resizedimage=resize(bi,jLabel2.getWidth(), jLabel2.getHeight());
ImageIcon resizedicon=new ImageIcon(resizedimage);
jLabel2.setIcon(resizedicon);
} catch (Exception ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
}
else {
System.out.println("File access cancelled by user.");
}
}
Assign your image to a string.
Eg image
Now set icon to a fixed size label.
image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));