Replace Image with out user noticing - image

I'm using JSF 2.1.7 + Prime Faces + Prime Faces Mobile.
I have a page that references a image:
<img src="/charts/chart1.png"/>
There's a separate background process that runs to update chart1.png every 2 minutes. (It gets the image from a particular online url). Here is the code I use to save the image:
public static String saveImage(final String strurl, final String imageFileName){
//assume the url for the image is valid
try {
URL url = new URL(strurl);
HttpURLConnection conn = (HttpURLConnection )url.openConnection();
conn.setConnectTimeout(1000); //1 sec timeout
conn.connect();
File file = new File(imageFileName);
BufferedImage image = ImageIO.read(conn.getInputStream());
ImageIO.write(image, "png", file);
return file.getAbsolutePath();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
ImageIO.write will delete the existing image file and write out a new one. I believe the above will result in a few milliseconds where the image file is not available, and hence the web user will not be able to see the image.
My questions are:
1) Is it true that there will be a time where the image is temporarily unavailable?
2) And if that is the case, what is a possible solution to fix this, so that user will always have a available image?
Thanks in advance. =)

Heres what i would do
1) First instead of replacing the image, i create a new image chart2.png
2)Then I would change the url in the IMG tag to point to a Servlet,
say
and in that servlet which will be mapped to /charts/showchart
,
And in the servlet i would check for latest available PNG , and stream it as response.
This way you customize how or what image you show.

Related

Save image in javaFX with applying effects on the image

I am making an application in JavaFX where the user can upload the photo and apply the effects on it, and in the end, save the image with the effects.
When I save the image, the original image is saved without the effects.
I get the image from the ImagView and save it in the file but the image is saved without the effects.
How I can solve this problem and have the picture with the effects that I applied to it?
The methods below the first one is to apply the effects and the second one is to save the image from ImageView
I need any idea to help me to solve this problem please.
\\Method of applying the filter
public void applyFilter(){
SepiaTone sepiaTone = new SepiaTone(cons);
myImgView.setEffect(sepiaTone);
}
public void saveImage() throws IOException {
Image imageToBeSaved = myImgView.getImage();// get the image from ImageView
File file = new File("D:/image.png");
try {
ImageIO.write (SwingFXUtils.fromFXImage(imageToBeSaved,null), "png", file);
}
catch (IOException e) {
e.printStackTrace();
}
}

update profile image functionality is not working while hosting as jar

Hi I am new to Springboot I was trying to develop a application, One of its functionality is to upload profile Image. It was working fine in STS but when I pack it in jar and hosting it on AWS EC2 envirnment I am getting some error while processing that image
Error:
handler for profile picture:
#PostMapping("/process-contact")
public String processContact(#ModelAttribute Contact contact, #RequestParam("profileImage") MultipartFile file,
HttpSession session) {
try {
contact.setUser(user);
user.getContacts().add(contact);
// processing and uploading photo
if (file.isEmpty()) {
System.out.println("File is empty");
contact.setImage("contact.png");
} else {
//Processing Image
InputStream inputStream = file.getInputStream();
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
Files.copy(inputStream, paths, StandardCopyOption.REPLACE_EXISTING);
contact.setImage(file.getOriginalFilename());
}
// Success Message
session.setAttribute("message", new Message("Your contact is added...", "success"));
this.userRepository.save(user);
System.out.println("Successfully Added");
} catch (Exception E) {
E.printStackTrace();
// Failed message
session.setAttribute("message", new Message("Something went wrong "+E.getMessage(), "danger"));
}
return "normal/add_contact_form";
}
It is working fine in IDE after some research I found way of writing data in jar is diffrent could some please help me how can I implemenr it for jar also.
Thankyou
all you need to do is replace this line:
Path paths = Paths.get(new ClassPathResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
With:
Path paths = Paths.get(new FileSystemResource("/static/img").getFile().getPath()+"/" +file.getOriginalFilename());
THat will work like charm.

write file into spring boot folder

my spring boot project structure is like this
src
|-main
|--|-java
|--|-resources
static
|-css
|-images
|-js
now I want to write a file into the static/images folder
I tried to new File like
BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream(new File("static/images")));it will throw "No such file or directory" exception
but in other html file I can get the js by "js/jsFile.js"
new File("static/images") is right
I used new File("/static/images") so I got an Exception
I was in the situation where using Spring Boot I had to save the image into one directory which is accessed statically.
Below code worked perfect
byte[] imageByteArray ....
String fileName = "image.png";
String fileLocation = new File("static\\images").getAbsolutePath() + "\\" + fileName;
FileOutputStream fos = new FileOutputStream(fileLocation);
fos.write(imageByteArray);
fos.close();
Hope it helped.
#zhuochen shen is correct.
The thing is to happen me is Eclipse doesn't show write file. So I looked at file explore. File is writing correctly.
try {
Path path=Paths.get("static/images/"+productDto.getImage().getOriginalFilename());
Files.write(path,productDto.getImage().getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
enter image description here
enter image description here

display pdf in browser using itext

i have modify a pdf with itext using pdfstamper. my application now create and save a new pdf file. i want to dipslay the pdf directly in the browser. Here my actual code
public static void test07(){
try{
PdfReader reader = new PdfReader("c:\\temp\\file.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("c:\\temp\\new.pdf"));
AcroFields form = stamper.getAcroFields();
//fill the fields
stamper.close();
reader.close();
} catch (Exception e){
e.printStackTrace();
}
}
The question is: How should I modify this code and the servlet to display the pdf file in the browser?
I have already tried with ByteArrayOutputStream and response.getOutputStream but nothing.
You're in luck! The book iText in Action contains a chapter that describes how to do exactly what you need. It's fairly straightforward: set the right headers on your response, and stream to the servlet's output stream.
Here's the link: http://itextpdf.com/examples/iia.php?id=173

How do you save images to a Blackberry device via HttpConnection?

My script fetches xml via httpConnection and saves to persistent store. No problems there.
Then I loop through the saved data to compose a list of image url's to fetch via queue.
Each of these requests calls the httpConnection thread as so
...
public synchronized void run()
{
HttpConnection connection = (HttpConnection)Connector.open("http://www.somedomain.com/image1.jpg");
connection.setRequestMethod("GET");
String contentType = connection.getHeaderField("Content-type");
InputStream responseData = connection.openInputStream();
connection.close();
outputFinal(responseData, contentType);
}
public synchronized void outputFinal(InputStream result, String contentType) throws SAXException, ParserConfigurationException, IOException
{
if(contentType.startsWith("text/"))
{
// bunch of xml save code that works fine
}
else if(contentType.equals("image/png") || contentType.equals("image/jpeg") || contentType.equals("image/gif"))
{
// how to save images here?
}
else
{
//default
}
}
What I can't find any good documentation on is how one would take the response data and save it to an image stored on the device.
Maybe I just overlooked something very obvious. Any help is very appreciated.
Thanks
I tried following this advise and found the same thing I always find when looking up BB specific issues: nothing.
The problem is that every example or post assumes you know everything about the platform.
Here's a simple question: What line of code writes the read output stream to the blackberry device? What path? How do I retrieve it later?
I have this code, which I do not know if it does anything because I don't know where it is supposedly writing to or if that's even what it is doing at all:
** filename is determined on a loop based on the url called.
FileOutputStream fos = null;
try
{
fos = new FileOutputStream( File.FILESYSTEM_PATRIOT, filename );
byte [] buffer = new byte [262144];
int byteRead;
while ((byteRead = result.read (buffer ))!=- 1)
{
fos.write (buffer, 0, byteRead);
}
fos.flush();
fos.close();
}
catch(IOException ieo)
{
}
finally
{
if(fos != null)
{
fos.close();
}
}
The idea is that I have some 600 images pulled from a server. I need to loop the xml and save each image to the device so that when an entity is called, I can pull the associated image - entity_id.png - from the internal storage.
The documentation from RIM does not specify this, nor does it make it easy to begin figuring it out.
This issue does not seem to be addressed on this forum, or others I have searched.
Thanks
You'll need to use the Java FileOutputStream to do the writing. You'll also want to close the connection after reading the data from the InputStream (move outputFinal above your call to close). You can find all kinds of examples regarding FileOutputStream easily.
See here for more. Note that in order to use the FileOutputStream your application must be signed.

Resources