How can I get an image too big from a server? - java

I'm currenty developing for blackberry and just bumped into this problem as i was trying to download an image from a server. The servlet which the device communicates with is working correctly, as I have made a number of tests for it. But it gives me the
413 HTTP error ("Request entity too large").
I figure i will just get the bytes, uhm, portion by portion. How can i accomplish this?
This is the code of the servlet (the doGet() method):
try {
ImageIcon imageIcon = new ImageIcon("c:\\Users\\dcalderon\\prueba.png");
Image image = imageIcon.getImage();
PngEncoder pngEncoder = new PngEncoder(image, true);
output.write(pngEncoder.pngEncode());
} finally {
output.close();
}
Thanks. It's worth mentioning that I am developing both the client-side and the server-side.

I am not aware by server side code. You can look on this Link to get an idea how to upload file using multipart to support Big files uploading
it can also work on blackberry , With some modifications needed.
http://www.developer.nokia.com/Community/Wiki/HTTP_Post_multipart_file_upload_in_Java_ME

I'm not familiar with the PNGEncoder class you're using, but just looking at your servlet code, and the comment you made about the request size (2.2 MB), I'm guessing that part of your problem is that you're uncompressing the image, and then transmitting it across the network.
I don't think you should have any PNGEncoder or ImageIcon code in your servlet. You should just read the "c:\\Users\\dcalderon\\prueba.png" file in with a normal InputStream as bytes, and then write that to the servlet's output. I don't think it matters whether that file is a PNG image, a .mp3 file, or any other content. (although you might need to set the Content Type to image/png).
So, I would try transmitting the image compressed (as a .png just as it's stored on disk). If that still doesn't work, then go with the suggestion to use multipart transmission.

Related

how can get album art of song from url

want get album art of song from url and this is my try so far :
SongPath = "www.asd.com/music.mp3";
android.media.MediaMetadataRetriever mmr = new MediaMetadataRetriever();
try{
mmr.setDataSource(SongPath);
}catch(Exception e){}
byte [] data = mmr.getEmbeddedPicture();
if(data != null)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
}
else
{
imageView.setImageResource(R.drawable.jak);
}
but when run this code get this : call to get embedded picture failed
so i research about this and some people fix that with change this part
mmr.setDataSource(SongPath);
to this
mmr.setDataSource(SongPath,new HashMap<String, String>());
i do that but when run app image view show nothing and get this : SkImageDecoder::Factory returned null
Note :
the only way i could do that use FFmpegMediaMetadataRetriever library (its like MediaMetadataRetriever) and worked but problem is library seems slow .. its mean 4,5sec time need to fetch pic and when add this library the apk file from 1.8mb become to 24mb! and this is so huge!
so any one in the world know how can do that with good way ? if any one can please help
You can use Glide in a similar way you would use it for a File: bumptech/glide#699 if you can figure out how to do it remotely. The problem is that you still need to download the whole .mp3 file, which takes that 4-5 seconds I guess. I'm not exactly sure about the .mp3 format, but I think the album art may be at the end of the file. For this reason this approach is not suggested (similar to how it's a bad idea to load video thumbs from http). If you want to go this way anyway, then slap a .diskCacheStrategy(SOURCE) on the load to save the file first, and then write a custom decoder to use
The best approach is to have the album art served from a separate file if you host the mp3; or use a public service to retrieve it. See any album art downloader program for possible services.
One thing's for sure: without a protocol, nothing will work, prefix your www. with http:// or https:// as necessary.

Struts2: How to store images outside of the webapp and save its path to the db?

Until now I did saving image into the webapp directory and its path into database.
But now am trying to save the image outside of the webapp so that if I deploy my new war files then my old files folder will not be deleted.
From my below code my image file is correctly saving into the specified folder outside of the webapp but i don't know how to retrieve that image into my jsp page.
I tried like this
<img src="www.myproject.com/struts2project/files/smile.jpg/>"
but this is wrong. I am not getting my image to be display into my jsp page.
Below code is working fine for uploading image into absolute path but my problem is how to retrieve that image?
`fileSystemPath= "/files";
try{
File destFile = new File(fileSystemPath, thempicFileName);
FileUtils.copyFile(thempic, destFile);
String path=fileSystemPath+"/"+thempicFileName;
theme=dao.getThemeById(themId);
theme.setThemeScreenshot(path);
theme.setThemeName(theme.getThemeName());
theme.setThemeCaption(theme.getThemeCaption());
dao.saveOrUpdateTheme(theme);
}catch(IOException e){
e.printStackTrace();
return INPUT;
}`
Kindly help me...
I hope I'm being clear on what I need, let me know if I am not and I'll try to explain in another way.
As you say . . . this question describes what you need to do. I guess what you need to know is how to best achieve this with struts 2. Here's what's going on.
In your tag:
That url is being routed to your struts 2 application. Correct? The context is "struts2project".
One of the solutions offered by the referenced question is to use Tomcat's ability to serve static requests and configure tomcat to know about this other document root that holds your images. I think this is a great solution.
If you want to keep it inside of struts2, I think you're best option is to use a dedicated "image streaming from that other place" action that get's an InputStream to the image, then uses the Struts2 Stream Result result type. That result type lets you specify an adhoc InputStream. It also helps you set the appropriate headers. Note, the header values on that documentation page are for downloading the file, so you don't want those values. They would force the browser to open a save as dialog for the image, I think.
You are already using absolute paths, just use a location outside of your web application:
String destinationDir = "/path/to/my/directory/";
File file = new File(destinationDir + item.getName());

Uploading a image to picasa, using a byte array

I have a byte[] of an image and I need to upload it as an image to picasa.
According to the documentation, an image is uploaded as follows.
MediaFileSource myMedia = new MediaFileSource(new File("lights.jpg"), "image/jpeg");
which means I need to create a File, out of the byte[].
The catch is, I have to do this without using FileOutputStream as it is not supported by Google App Engine (which is the environment I am using)
Is there any way to do this?
You don't have to use MediaFileSource to upload a photo, you can use MediaByteArraySource and pass it to photo.setMediaSource(...).

What is the correct path for Toolkit.getImage()?

I need to upload an image file and generate a thumbnail for the uploaded file in my JSF webapplication. The original image is stored on the server in /home/myname/tomcat/webapps/uploads, while the thumbnail is stored in /home/myname/tomcat/webapps/uploads/thumbs. I'm using the thumbnail generator class I copied from philreeve.com.
I have successfully uploaded the file with help from BalusC. But using Toolkit.getImage(), I can't access the image.
I used the uploaded file's absolute path, like so:
inFilename = file.getAbsolutePath();
The relevant code from the thumbnail generator is:
public static String createThumbnail(String inFilename, String outFilename, int largestDimension) {
...
Image inImage = Toolkit.getDefaultToolkit().getImage(inFilename);
if (inImage.getWidth(null) == -1 || inImage.getHeight(null) == -1) {
return "Error loading file: \"" + new File(inFilename).getAbsolutePath() + "\"";
}
...
}
Since I am already using the absolute path, I don't understand why it is not working. I have also used the following values for inFilename, but I always get the "Error loading file...".
/home/myname/tomcat/webapps/uploads/filename.ext
/uploads/filename.ext
But I did check the directory, and the image is there. (I uploaded using /home/myname/tomcat/webapps/uploads/filename.ext, and it works.) What is the correct path for the image in that directory? Thank you.
Update
I got the code to work by using:
Image inImage = ImageIO.read(new File(inFilename));
I still don't understand why Toolkit.getImage() does not work though.
Are you sure it's a JPEG file? Use an image viewer to make sure nothing bad happened to the file during upload (or that it was an image to begin with).
Also, use new File(inFilename).exists() to make sure the path is correct. I also suggest to print new File(inFilename).getAbsolutePath() in error messages because relative paths can hurt you.
That said, the rest of the code looks correct.
The problem is that Toolkit.getImage() does not return the image immediately. The issue is well-described in this bug report, a relevant extract of which is here:
This is not a bug. The submitter is not properly using the asynchronous
Image API correctly. He assumes that getImage loads all of the image's bits
into memory. However, it is well documented that the actual loading of
bits does not take place until a call to Component.prepareImage or
Graphics.drawImage. In addition, these two functions return before the
Image is fully loaded. Developers are required to install an ImageObserver
to listen for notification that the Image has been fully loaded. Once they
receive this notification, they can repaint the Image.
I found that the answer to this question works well:
Image image = new ImageIcon(this.getClass().getResource("/images/bell-icon16.png")).getImage();

Java file IO and "access denied" errors

I have been tearing my hair out on this and thus I am looks for some help .
I have a loop of code that performs the following
//imports ommitted
public void afterPropertiesSet() throws Exception{
//building of URL list ommitted
// urlMap is a HashMap <String,String> created and populated just prior
for ( Object urlVar : urlMap.keySet() ){
String myURLvar = urlMap.get(urlVar.toString);
System.out.println ("URL is "+myURLvar );
BufferedImage imageVar = ImageIO.read(myURLvar);//URL confirmed to be valid even for executions that fail
String fileName2Save = "filepath"// a valid file path
System.out.println ("Target path is "+fileName2Save );
File file2Save = new File (fileName2Save);
fileName2Save.SetWriteable(true);//set these just to be sure
fileName2Save.SetReadable(true);
try{
ImageIO.write (imageVar,"png",file2save)//error thrown here
}catch (Exception e){
System.out.println("R: "+file2Save.canRead()+" W: "+file2Save.canWrite()+" E:"+file2Save.canExecute()+" Exists: "+file2Save.exists+" is a file"+file2Save.isFile() );
System.out.println("parent Directory perms");// same as above except on parent directory of destination
}//end try
}//end for
}
This all runs on Windows 7 and JDK 1.6.26 and Netbeans,Tomcat 7.0.14 . The target directory is actually inside my netbeans project directory in a folder for a normal web app ( outside WEB-INF) where I would expect normally to have permission to write files.
When the error occurs I get one of two results for the file a.) All false b.)all true. The Parent directory permission never change all true except for isFile.
The error thrown ( java.IO.error with "access denied" ") does not occur every time ... in fact 60% of the time the loop runs it throws no error. The remaining 40% of the time I get the error on 1 of the 60+ files it writes. Infrequently the same one. The order in which the URLs it starts from changes everytime so the order in which the files are written is variable. The file names have short concise names like "1.png". The images are small..less then 8k.
In order to make sure the permissions are correct I have :
Given "full control" to EVERYONE from the net beans project directory down
Run the JDK,JRE and Netbeans as Administrator
Disabled UAC
Yet the error persists. Google searches for this seem to run the gamut and often read like vodoo. Clearly I ( and Java and Netbeans etc ) should have permission to write a file to the directory .
Anyone have any insight ? This is all ( code and the web server hosting the URL) on a closed system so I can't cut and paste code or stacktrace.
Update: I confirmed the imageURL is valid by doing a println & toString prior to each read. I then confirmed that a.) the web server hosting the target URL returned the image with a http 200 code b.) that the URL returned the image when tested in a web browser. In testing I also put a if () in after the read to confirm that the values was not NULL or empty. I also put in tests for NULL on all the other values . They are always as expected even for a failure .The error always occurs inside the try block. The destination directory is the same every execution. Prior to every execution the directory is empty.
Update 2: Here is one of the stack traces ( in this case perms for file2Save are R: True W:True E: True isFile:True exists:True )
java.io.FileNotFoundException <fullFilepathhere> (Access is denied)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)
at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:53)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:37)
at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:393)
at javax.imageio.ImageIO.write(ImageIO.java:1514)
at myPackage.myClass.afterPropertiesSet(thisClassexample.java:204)// 204 is the line number of the ImageIO write
This may not answer your problem since there can be many other possibilties to your limited information.
One common possibilty for not being able to write a file in web application is the file locking issue on Windows if the following four conditions are met simultaneously:
the target file exists under web root, e.g. WEB-INF folder and
the target file is served by the default servlet and
the target file has been requested at least once by client and
you are running under Windows
If you are trying to replace such a file that meets all of the four conditions, you will not be able to because some servlet containers such as tomcat and jetty will buffer the static contents and lock the files so you are unable to replace or change them.
If your web application has exactly this problem, you should not use the default servlet to serve the file contents. The default servlet is desigend to serve the static content which you do not want to change, e.g. css files, javascript files, background images, etc.
There is a trick to solve the file locking issue on Windows for jetty by disabling the NIO http://docs.codehaus.org/display/JETTY/Files+locked+on+Windows
The trick is useful for development process, e.g. you want to edit the css file and see the change without restarting your web application, but it is not recommended for production mode. If your web application relies on this trick in the production process, then you should seriously consider redesign your codes.
I cannot tell you what's going on or why... I have a feeling that it's something dependent on the way ImageIO tries to save the image. What you could do is saving the BufferedImage by leveraging the ByteArrayOutputStream as described below:
BufferedImage bufferedImage = ImageIO.read(new File("sample_image.gif"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bufferedImage, "gif", baos );
baos.flush(); //Is this necessary??
byte[] resultImageAsRawBytes = baos.toByteArray();
baos.close(); //Not sure how important this is...
OutputStream out = new FileOutputStream("myImageFile.gif");
out.write(resultImageAsRawBytes);
out.close();
I'm not really familiar with the ByteArrayOutputStream, but I guess its reset() function could be handy when dealing with saving multiple files. You could also try using its writeTo(OutputStream out) if you prefer. Documentation here.
Let me know how it goes...

Categories