Issue in saving image to desktop - java

Trying to save a image from this URL which gets transformed to a image. Looks like I am missing something, the image is not getting saved on the desktop
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
public class Image {
public static void main(String[] args) {
BufferedImage image = null;
try {
String url = "http://ramp.sdr.co.za/zp-core/i.php?a=1402NYFW/NicholasK&i=1402_NYFW_1005_NicholasK.JPG&w=387&h=580&cw=&ch=&q=92&wmk=!";
String imgPath = null;
imgPath = "C:/temp" + "a" + "";
URL imageUrl = new URL(url);
image = ImageIO.read(imageUrl);
if (image != null) {
System.out.println("in here");
File file = new File(imgPath);
ImageIO.write(image, "jpg", file);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

You may not have appropriate user privileges to write to "C:/tempa". Event if you decided to use "c:/temp", the folder may not exist and you may not have the required privileges to either create it or write to it.
You could use System.getProperties("user.home"), which will return the current users home directory, which is more likely to allow you to write to it
String imgPath = System.getProperties("user.home") + "/a image.jpg";
File file = new File(imgPath);
ImageIO.write(image, "jpg", file);
I'd also add a else statement to your if statement so you can see when the image didn't load

Related

How to Get Total Page Count From Tiff

I have started to create a new method in our project to return total pages. We are using TIFFTweaker which can be referenced from the following URL - https://github.com/dragon66/icafe/blob/master/src/com/icafe4j/image/tiff/TIFFTweaker.java
In this class I found a method TIFFTweaker.getPageCount() which looks like it wants a RandomAccessInputStream object for their getPageCount().
I've been playing around with trying to get from my file object over to what they're looking for.
What would be the best way to approach this and return the total pages from the tiff?
I have looked over some java docs, stackOverflow and some random blogs but can't seem to figure out how to get from a file object to a randomaccessinputstream.
#Override
public Integer totalPages(File file) {
Integer numberOfPages = 0;
try{
//TIFFTweaker.getPageCount(); - How to pass the file and get the count? Problem is type is a random access input stream and I have a file type
FileInputStream fileInputStream = new FileInputStream(file);
String absolutePath = file.getAbsolutePath();
// return TIFFTweaker.getPageCount();
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
I am expecting a numeric value returned which represents the total number of pages in the TIFF file I'm passing.
Here is what I got to work. #roeygol, thanks for your answer. I had tried to Maven import the dependency but something was broken in that version. Here is what I came up with.
#Override
public Integer totalPages(File file) {
try(
InputStream fis = new FileInputStream(file);
RandomAccessInputStream randomAccessInputStream = new
FileCacheRandomAccessInputStream(fis)
){
return TIFFTweaker.getPageCount(randomAccessInputStream);
}catch(IOException e){
log.error("Error with Tiff File" + e);
}
return null;
}
Try to use this code:
import java.io.File;
import java.io.IOException;
import java.awt.Frame;
import java.awt.image.RenderedImage;
import javax.media.jai.widget.ScrollingImagePanel;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class MultiPageRead extends Frame {
ScrollingImagePanel panel;
public MultiPageRead(String filename) throws IOException {
setTitle("Multi page TIFF Reader");
File file = new File(filename);
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
System.out.println("Number of images in this TIFF: " +
dec.getNumPages()); //<< use this function to get the number of pages of your TIFF
// Which of the multiple images in the TIFF file do we want to load
// 0 refers to the first, 1 to the second and so on.
int imageToLoad = 0;
RenderedImage op =
new NullOpImage(dec.decodeAsRenderedImage(imageToLoad),
null,
OpImage.OP_IO_BOUND,
null);
// Display the original in a 800x800 scrolling window
panel = new ScrollingImagePanel(op, 800, 800);
add(panel);
}
public static void main(String [] args) {
String filename = args[0];
try {
MultiPageRead window = new MultiPageRead(filename);
window.pack();
window.show();
} catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
Prerequisites for this code is to use jai-codec:
https://mvnrepository.com/artifact/com.sun.media/jai-codec/1.1.3
The main function to be used for is getNumPages()

Problem with colors after converting image

I have a class which converts images from PNG to JPG (for space saving reasons). My problem is that most of images goes form this to this. [
Currently I found only two pictures that are not affected by conversion gallery but if you're using default windows 10 pictures app windows ignores them when going through pictures. If I open them app behaves like this is only picture in folder even if this isn't true.
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
public class PNG2JPG {
boolean status;
PNG2JPG(String path,float quality){
File file = new File(path);
try {
BufferedImage image = ImageIO.read(file);
String fileName = file.getName();
path = path.substring(0,path.lastIndexOf('\\'));
fileName = fileName.substring(0,fileName.lastIndexOf('.'));
JPEGImageWriteParam jpegParams = new JPEGImageWriteParam(null);
jpegParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(quality); //Quality from 0 to 1
final ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next();
writer.setOutput(new FileImageOutputStream(
new File(path + "/" + fileName + ".jpg")));
writer.write(null, new IIOImage(image, null, null), jpegParams);
status = true;
}
catch (IOException e){
System.out.println("No file found");
status = false;
}
}
}

Tess4j jar file issue

import java.awt.image.RenderedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import net.sourceforge.tess4j.Tesseract;
public class Tess4JSample {
public static void main(String[] args) throws Exception{
URL imageURL = new URL("http://s4.postimg.org/e75hcme9p/IMG_20130507_190237.jpg");
RenderedImage img = ImageIO.read(imageURL);
File outputfile = new File("saved.png");
ImageIO.write(img, "png", outputfile);
try {
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
String result = instance.doOCR(outputfile);
System.out.println(result);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
for this program I have put the jar files tess4j-1.5.0 and jai_imageio-1.1. But still it shows error
The import net.sourceforge cannot be resolved
Can anyone tell me what is the necessary action needs to be taken care for error resolution? I taken this program from stack overflow itself. Thanks! in advance.

Throws file not found Exceptions

I created a gfx folder inside an android project's assets folder. I stored images which i will be using in my game for android. Since i need to pass the image height and image width converting it to the nearest highest powwer of 2 in andEngine, so i create a ImageUtility class to read image inside the gfx folder and get its height and width.
package org.ujjwal.androidGameUtility;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageUtilities {
private static final String ABSOLUTE_PATH = "F:\\Games\\TowerOfHanoi\\assets\\gfx\\";
private String fileName = "";
private File imageFile;
private int imageHeight;
private int imageWidth;
public ImageUtilities(String filename){
this.fileName = filename;
this.imageFile = new File(ABSOLUTE_PATH + this.fileName);
try {
processImage();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* this methods set the doucment relative path for the graphics to be used
* and it is mandotry to call before using ImageUtilties object else it will throw filenotFoundException
*
* #param path
*/
private void processImage() throws FileNotFoundException{
if(imageFile.exists()){
try {
BufferedImage image = ImageIO.read(this.imageFile);
this.imageWidth = image.getWidth();
this.imageHeight = image.getHeight();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else{
throw new FileNotFoundException("Either you missed typed filename or haven't called setAssetBasePathMethod setImageBasePath(String path) method");
}
}
public int getImageHeight(){
return this.imageHeight;
}
public int getImageWidth(){
return this.imageWidth;
}
public String getFileName(){
return this.fileName;
}
public File getImageFile(){
return this.imageFile;
}
}
I always get FileNotFoundException with the error msg above. The weird problem is when i access the image file from other java class i don't get any error. I printed the height and width all went exactly i wanted but i could not access the same image file from my android game project. What kind of error is this. I provided absolute filepath for the image. I also tried to compare the file path they were same. Please tell me what error i got, I spend whole day trying to figure out but ...
What #mittmemo mentioned was right, you cannot access the F drive from your phone or emulator. Your computer and android are two different OS. What you can do is instead of putting your file in /assets, you can put it in /raw under resource directory. You can then access it by using:
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String str = new String(b);
} catch (Exception e) {
Log.e(LOG_TAG, "File Reading Error", e);
}

Saving internet icon then re-opening causes EOF with image4j

I'm currently working on a project where I'm attempting to download a .ico file, but for some strange reason, I can't seem to open it programmatically once downloaded. I can however, open the image saved using any image editor or viewer. My code:
public static BufferedImage parseImageLocal(String url) throws IOException {
if (url.endsWith(".ico")) {
return ICODecoder.read(new File(url)).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(new File(url));
} else {
return ImageIO.read(new File(url));
}
}
public static void saveImage(BufferedImage img, String path)
throws IOException {
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
if (!outputfile.exists()) {
outputfile.createNewFile();
}
if (path.endsWith(".ico")) {
ICOEncoder.write(img, outputfile);
} else if (path.endsWith(".bmp")) {
BMPEncoder.write(img, outputfile);
} else {
ImageIO.write(img, "png", outputfile);
}
}
And this is how i download images from the internet:
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
The error is on this line:
return ICODecoder.read(new File(url)).get(0);
It "seems" that you are trying to download the icon from the internet, but you are trying to treat the URL as a File.
Basically, this isn't going to be possible, File won't be able to resolve to an actual physical file.
Instead, you should be using ICODecoder#read(InputStream) and URL#openStream
Something more like...
BufferedImage img = null;
InputStream is = null;
try {
// url begin an instance of java.net.URL
is = url.openStream();
img = ICODecoder.read(is);
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
return img;
Updated with example
A web resource is not a File, you can not access it as if they were, instead, you need to use the classes designed for interacting with the internet/network.
For example...
import java.awt.EventQueue;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.sf.image4j.codec.ico.ICODecoder;
public class ReadFavicon {
public static void main(String[] args) {
new ReadFavicon();
}
public ReadFavicon() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
try {
BufferedImage img = readIcon(new URL("https://secure.gravatar.com/favicon.ico"));
JOptionPane.showMessageDialog(null, "My FAVICON", "Icon", JOptionPane.PLAIN_MESSAGE, new ImageIcon(img));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public BufferedImage readIcon(URL url) throws IOException {
BufferedImage img = null;
InputStream is = null;
try {
// url begin an instance of java.net.URL
is = url.openStream();
List<BufferedImage> imgs = ICODecoder.read(is);
img = imgs != null ? imgs.size() > 0 ? imgs.get(0) : null : null;
} finally {
try {
is.close();
} catch (Exception exp) {
}
}
return img;
}
}
Update with some more ideas
Now. I could be wrong, but when I ran your code, I ran into a serious of problems with the paths...
Let's assume the original url/path is https://secure.gravatar.com/favicon.ico, when you save the image, you do something like...
File outputfile = new File(path.replace("http://", ""));
File parent = outputfile.getParentFile();
parent.mkdir();
With our original path, this would result in a outputfile of https://secure.gravatar.com/favicon.ico, which is obviously wrong...
We can correct for this by using path.replace("https://", "") as well...
path = path.replace("http://", "");
path = path.replace("https://", "");
File outputfile = new File(path);
File parent = outputfile.getParentFile();
parent.mkdir();
Now, this results in a outputfile of secure.gravatar.com/favicon.ico. I become a little unstuck, as I'm not sure if this is what you want...but it does work for me...
Now, when you read the file, you do something like this...
public static BufferedImage parseImage(String url) throws IOException {
URL dest = new URL(url);
if (url.endsWith(".ico")) {
return ICODecoder.read(dest.openStream()).get(0);
} else if (url.endsWith(".bmp")) {
return BMPDecoder.read(dest.openStream());
} else {
return ImageIO.read(dest);
}
}
Now, with no evidence to the contray, I have to assume the url has not changed and is still https://secure.gravatar.com/favicon.ico...this means that new File("https://secure.gravatar.com/favicon.ico") will produce an invalid file reference
So, again, I parsed the input...
url = url.replace("https://", "");
url = url.replace("http://", "");
File outputfile = new File(url);
String parentPath = outputfile.getParent();
String name = outputfile.getName();
url = parentPath + File.separator + name;
Which produces secure.gravatar.com\favicon.ico
This all downloaded, wrote and read without error.

Categories

Resources