converting .webp to .jpeg using Java - java

i want to convert a .webp image to .jpeg. I have used javax.imageio.ImageIO.
but # line no: 19 bImage = ImageIO.read(fis); returns a null for webp images.
Code is working fine if I try to convert .png ,.gif file format..
can any one help?
public static void imageIoWrite() {
BufferedImage bImage = null;
try {
File initialImage = new File("resources/1.webp");
FileInputStream fis = new FileInputStream(initialImage);
bImage = ImageIO.read(fis); //why it returns null?
if (bImage != null) {
ImageIO.write(bImage, "jpg",
new File("resources/NewImage1.jpg"));
System.out.println("Image file written successfully");
} else {
System.out.println("imag is empty");
}
} catch (IOException e) {
System.out.println("Exception occured :" + e.getMessage());
}
}

It seems that ImageIO is not able to read webp images. As you can read in the docs, the method read returns null in this case. I think that you have to use an additional library to read and write webp images.

Related

How to set a standard image to show if a search for associated image name yields no results?

I am working on a project for my course and have been asked to show an associated image for products in a system, the user can add products, and he enters the name of the image file whilst doing so. the program then finds the image file and displays it with the product information.
I would like to add some additional code so that if there is no image file matching the string input that a standard image is shown. The code I have so far either shows the image file if it is found or does not show anything. can someone show me how to modify it so that it can show a standard image if no associated image file is found. the standard image is simply "no-image-found.jpg". Here is the code:
public void showImage(JLabel imageArea, String image){
BufferedImage img = null;
try {
img = (BufferedImage)ImageIO.read(new File(image));
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
any help is very much appreciated, and my sincere apologies if this is a noob question, I am quite new to java.
In the catch, you could load the standard image and show it
Basically check for image existence assuming path is valid otherwise get the standard image. You can have something similar:
public void showImage(JLabel imageArea, String image)
{
BufferedImage img = null;
try
{
file = new File(image);
if (file.exists())
{
img = ImageIO.read(file);
}
else
{
file = new File(standardImagePath);
img = ImageIO.read(file);
}
Image actualimage = img.getScaledInstance(imageArea.getWidth(), imageArea.getHeight(), 0);
imageArea.setIcon(new ImageIcon(actualimage));
}
catch (IOException e)
{
System.out.println(e.getMessage());
}

Problem saving image in external storage on android

I am writing a camera application for the android platform. I am using the CameraKitView Library for producing my camera view. Everything else including accessing the camera is working as expected except for actually capturing and saving the image. minimum sdk is 15 and target sdk and compile sdk is 28. The code for saving the image is as shown below
cameraKitView.captureImage(new CameraKitView.ImageCallback() {
#Override
public void onImage(CameraKitView cameraKitView, byte[] photo) {
File savedPhoto = new File(Environment.getExternalStorageDirectory(), "pchk.jpg");
try{
FileOutputStream outputStream = new FileOutputStream(savedPhoto.getPath());
outputStream.write(photo);
outputStream.close();
}catch (java.io.IOException e){
e.printStackTrace();
}
}
});
Thank you in advance for your assistance
First of all verify that your file or folder where you want to save a file is exists or not, if not create them
capturedFolderPath is a path of the folder where you want to create the file
File folderFile = new File(capturedFolderPath)
if (!folderFile.exists()) {
folderFile.mkdirs();
}
String imageNameToSave = "xyz.jpg";
String imagePath = capturedFolderPath
+ File.separator + imageNameToSave + ".jpg";
File photoFile = new File(imagePath);
if (!photoFile.exists()) {
photoFile.createNewFile();
}
after creating write the bytes on the file like this
FileOutputStream outputStream = new FileOutputStream(photoFile);
outputStream.write(bytes);
outputStream.close();

Apache PDFBox refuses to open temporary created PDF file

I am creating desktop JavaFX application for viewing PDF files. PDFs are at resource folder. I read resourse file as stream, then I create temporary file and use it to convert contents to image and show into ImageView.
currentPdf = new File("current.pdf");
if (!currentPdf.exists()) {
// In JAR
InputStream inputStream = ClassLoader.getSystemClassLoader()
.getResourceAsStream("PDFSample.pdf");
// Copy file
OutputStream outputStream;
try {
outputStream = new FileOutputStream(currentPdf);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
byte[] buffer = new byte[1024];
int length;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
The problem is: when I create regular file with
currentPdf = new File("current.pdf");
Everything works as expected (i get current.pdf created at directory where jar is located). But I want the file to be created at system temp folder and to be deleted on exit from application. I tried this:
try {
currentPdf = File.createTempFile("current",".pdf");
} catch (IOException e) {
throw new RuntimeException(e);
}
currentPdf.deleteOnExit();//also tried to comment this line
And get exception:
Caused by: java.io.IOException: Error: End-of-File, expected line
at org.apache.pdfbox.pdfparser.BaseParser.readLine(BaseParser.java:1517)
at org.apache.pdfbox.pdfparser.PDFParser.parseHeader(PDFParser.java:360)
at org.apache.pdfbox.pdfparser.PDFParser.parse(PDFParser.java:186)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1227)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1194)
at org.apache.pdfbox.pdmodel.PDDocument.load(PDDocument.java:1165)
at ua.com.ethereal.pdfquiz.Controller.getPdfPageAsImage(Controller.java:147)
At this method:
#SuppressWarnings("unchecked")
public static Image getPdfPageAsImage(File pdfFile, int pageNum) {
Image convertedImage;
try {
PDDocument document = PDDocument.load(pdfFile);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
PDPage page = list.get(pageNum);
BufferedImage image = page.convertToImage(BufferedImage.TYPE_INT_RGB, 128);
convertedImage = SwingFXUtils.toFXImage(image, null);
document.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
return convertedImage;
}
Would appreciate help in resolving this or pointing me on way to read file directly from jar to avoid creating temporary copies.
How do you create the temporary file?
The usual methods make an empty file in the filesystem. That will trip your logic here:
if (!currentPdf.exists()) {
That check is supposedly there to avoid overwriting exiting files, but in this case you have to get rid of it. As it is, you skip your PDF generation code and try to read an empty file.

The inline attachment i save to disk is corrupted

I have a piece of code that read my inbox email. the code identify 2 kind of attachments:
1) The attached files, which are downloaded and saved to a database. This works just fine.
2) The inline attachment (I'm using an image as the attachment in my tests). The code detects this kind of attachment, but when I save them to disk the file seems to be corrupted. I checked the file properties generated and noticed that it had no basic info (pixels, height, width) with it. I think the file is not saved properly when downloaded to disk (I have tried PNG and JPG). I think the file needs to be saved with a kind of mimetype properties so i can open it properly. Any tips please? Thanks in advance.!
Here is a snip of my code:
public void procesMultiPart(Multipart content) throws SQLException {
try {
for (int i = 0; i < content.getCount(); i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
String downloadDirectory = "D:/Attachment/";
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println("procesMultiPart es plainText");
} else if (null != bodyPart.getDisposition() && bodyPart.getDisposition().equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("IS ATTACHMENT...");
// i save the attachment to database and is OK..
} else if (bodyPart.getDisposition() == null){
System.out.println("IS AN INLINE ATTACHMENT...");
String fileNameinline = "inline" + i + ".png";
InputStream inStream = bodyPart.getInputStream();
FileOutputStream outStream = new FileOutputStream(new File(downloadDirectory + fileNameinline), true);
byte[] tempBuffer = new byte[4096];// 4 KB
int numRead;
while ((numRead = inStream.read(tempBuffer)) != -1) {
outStream.write(tempBuffer);
}
inStream.close();
outStream.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
The file is corrupted because you are writing it to the disc incorrectly:
outStream.write(tempBuffer);
You should only write as many bytes as you read:
outStream.write(tempBuffer, 0, numRead);
Thanks to everyone for help and tips. I solved the problem. This is how i did it: I notice that when read the email body (where supposes there was just the pasted image) , there was more that just the image, there was a kind of HTML too, so in other words, the body part has multiparts (2 parts in my case), so i have to process each part until find the image, so i can save it.
hope this help someone else.
regards.

ImageIO.write didn't work?

Hello I have problem with followed function that should save forwarded bufferedImage on disk. When I run this code there no exception throwed no problems, BufferedImage is transfered to ImageIO.write(img, ext ,fileToSave) file was created, ext is correct but there no image on my disk! After hours i dont have idea what can go wrong. Maybe permission? But i have it to read/write on disk.
public boolean SaveImage(BufferedImage img)
{
JFileChooser FC=new JFileChooser("C:/");
FC.addChoosableFileFilter(new jpgSaveFilter());
FC.addChoosableFileFilter(new jpegSaveFilter());
FC.addChoosableFileFilter(new PngSaveFilter());
FC.addChoosableFileFilter(new gifSaveFilter());
FC.addChoosableFileFilter(new BMPSaveFilter());
FC.addChoosableFileFilter(new wbmpSaveFilter());
int retrival=FC.showSaveDialog(null);
if (retrival == FC.APPROVE_OPTION)
{
String ext="";
String extension=FC.getFileFilter().getDescription();
if(extension.equals("*.jpg,*.JPG"))
{
ext=".jpg";
}
if(extension.equals("*.png,*.PNG"))
{
ext=".png";
}
if(extension.equals("*.gif,*.GIF"))
{
ext=".gif";
}
if(extension.equals("*.wbmp,*.WBMP"))
{
ext=".wbmp";
}
if(extension.equals("*.jpeg,*.JPEG"))
{
ext=".jpeg";
}
if(extension.equals("*.bmp,*.BMP"))
{
ext=".bmp";
}
File fileToSave = FC.getSelectedFile();
try{
ImageIO.write(img, ext ,fileToSave);
}
catch (IOException e) {
e.printStackTrace();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
return false;
}
return true;
}
return false;
}
Thanks for help!
The problem is your specifying the file format as the ext
Effectively your saying
ImageIO.write(img, ".jpg" ,fileToSave)
You need to supply it so it evaluates to
ImageIO.write(img, "jpg" ,fileToSave)
Extensions in ImageIO.write should be like "PNG", "JPG". without the point.
And the if (extension.equals("...")) approach is very bad. Make sure you actually provided an extension. IE: at least one of the if's succeeded. Try to print the ext just before writing, to check if it has a correct value.
System.out.println("Extension: " + ext);
Oh, and javax.imageio only supports PNG, JPG, JPEG (and GIF read-only). To get dynamically a list of supported formats, use:
ImageIO.getWriterFormatNames();
mistake may be here: JFileChooser FC=new JFileChooser("C:/");
change the file path to "C:\" (or double backslash)

Categories

Resources