Wicket create image from file system outside web application directory - java

I have a repository storing many images somewhere on the server.
I want to be able to create a dynamic Image object with one of the images stored in my repository.
I am using wicket 1.5.7. I saw this example somewhere
1) Created the FileResource class:
public class FileResource extends WebResource {
private static final long serialVersionUID = 1L;
private File file;
public FileResource(File file) {
this.file = file;
}
#Override
public IResourceStream getResourceStream() {
return new FileResourceStream(file);
}
}
2) In MyPage.java:
File imageFile = new File("local_path_to_image");
Image myImage = new Image("myImage", new FileResource(imageFile));
add(myImage);
3) In MyPage.html:
<i-m-g wicket:id="myImage" />
But this is not working in my case because WebResource is not available in my wicket 1.5.
I have also studied this link in wicket action. But I am a wicket bignner i could not understand much.
I am making a project in which user when click on a product a modal window open with the product name. I also want to include the product image on my modal window inside a panel. Images are stored on my server in a directory.
Any help and advices appreciated! Thanks in advance.

finally i settled on this code. I am passing image file name and creating image.
add(new NonCachingImage("imgPlc", new AbstractReadOnlyModel<DynamicImageResource>(){
#Override public DynamicImageResource getObject() {
DynamicImageResource dir = new DynamicImageResource() {
#Override protected byte[] getImageData(Attributes attributes) {
StringValue name = parameters.get("name");
byte[] imageBytes = null;
if(name.isEmpty() == false)
imageBytes = getImageAsBytes(name.toString());
return imageBytes;
}
};
dir.setFormat("image/png");
return dir;
}
}));

Related

Scale image with Vaadin and Java

I have following code to upload an image and show it on the webpage
// Show uploaded file in this placeholder
final Embedded image = new Embedded("Uploaded Image");
image.setVisible(false);
// Implement both receiver that saves upload in a file and
// listener for successful upload
class ImageUploader implements Receiver, SucceededListener {
public File file;
public OutputStream receiveUpload(String filename, String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
try {
// Open the file for writing.
file = new File(tmp_dir + "/" + filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
return null;
}
return fos; // Return the output stream to write to
}
public void uploadSucceeded(SucceededEvent event) {
// Show the uploaded file in the image viewer
image.setVisible(true);
image.setSource(new FileResource(file));
}
};
ImageUploader receiver = new ImageUploader();
// Create the upload with a caption and set receiver later
Upload upload = new Upload("Upload Image Here", receiver);
upload.setButtonCaption("Start Upload");
upload.addSucceededListener(receiver);
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, image);
The problem is, it shows the full resolution and I want to scale (so it remains proportional) it down to 180px width. The picture also needs to be saved as the original filename_resized.jpg but I can't seem to get it to scale. Several guides on the web talk about resizing (but then the picture gets distorted) or it gives some issues with Vaadin.
Update:
Added the scarl jar (from this answer)) because it would be easy-peasy then by using following code:
BufferedImage scaledImage = Scalr.resize(image, 200);
but that gives following error:
The method resize(BufferedImage, int, BufferedImageOp...) in the type Scalr is not applicable for the arguments (Embedded, int)
and I cannot cast because Cannot cast from Embedded to BufferedImage error
Update: with following code I can cast to the right type
File imageFile = (((FileResource) (image.getSource())).getSourceFile());
BufferedImage originalImage = ImageIO.read(imageFile) ;
BufferedImage scaledImage = Scalr.resize(originalImage, 200);
but now I can't show the image..
final FormLayout fl = new FormLayout();
fl.setSizeUndefined();
fl.addComponents(upload, scaledImage);
because of error The method addComponents(Component...) in the type AbstractComponentContainer is not applicable for the arguments (Upload, BufferedImage)
You cannot use Vaadin objects directly with a third-party tool such as Scalr without adapting one to the other. "Embedded" is a Vaadin class whereas SclaR expects a "BufferedImage".
So, you first need to extract the File object from the Embedded object:
File imageFile = ((FileResource)(image.getSource()).getSourceFile();
Then, load it into the BufferedImage using ImageIO, such as explained in the link you pointed at ( What is the best way to scale images in Java? )
BufferedImage img = ImageIO.read(...); // load image
Then, you have the BufferedImage object you were looking for.

GWT export table

I am new in GWT and I am working on a project where GWT is used to generate a form. In this form I have added a table in a Vertical panel. Now I want to export this table in excel or CSV. Wondering if someone can help me on this issue.
This is sample code of the entry point class:
public class ItemListEditor implements EntryPoint
{
private final Button addRow = new Button("Add Row");
private final Button save = new Button("Save");
private final Button next = new Button("Next");
private final Button upload = new Button("Upload");
private final Button export = new Button("Export");
private ItemTable table = null;
}
Again, my problem is only to export this table- like when click on export button, system will ask for the location.
I can provide more information if needed.
Please help on this issue
Create a HTTPServlet class, inside the doGet() method of the servlet create a HSSFWorbook using the Apache Poi jar, write your data in the sheet, write the workbook in the response part of servlet.
Map the servlet in your web.xml file and finally, use this servlet url inside your button handler..
EDITED ----->
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent arg0) {
exlGenerationServiceAsync.excelReportObjects(new AsyncCallback() {
#Override
public void onFailure(Throwable arg0) {
arg0.printStackTrace();
}
#Override
public void onSuccess(Object arg0) {
Window.open(GWT.getModuleBaseURL() + "url", "", "");
}
});
}
}
Servlet mapping inside the web.xml file----->
<servlet>
<servlet-name>excelFile</servlet-name>
<servlet-class>com.company.server.excelFileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>excelFile</servlet-name>
<url-pattern>/yourUrl</url-pattern>
</servlet-mapping>
Where excelFileServlet is my servlet class.
Inside Servlet class---->
File file = new File("Path Where you want to write your excel file");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=" + "Excel_Report_Name.xls");
response.setContentLength((int) file.length());
FileInputStream fileInputStream = new FileInputStream(file);
try{
OutputStream responseOutputStream = response.getOutputStream();
int bytes;
while ((bytes = fileInputStream.read()) != -1) {
responseOutputStream.write(bytes);
}
responseOutputStream.close();
}catch(Exception e){
e.printStackTrace();
System.err.println("Inside Try/catch");
If you're looking for some quick and raw exportation, you can give a try to https://code.google.com/p/gwt-table-to-excel/. The project is not very active.
Otherwise, if you want to have more control on the formatting and data you have to send the content of the table to the server side using RPC or other, and then you can use Apache POI to export it as you do usually in Java.

Create a public folder in internal storage

Sorry for my English, but I want to write in this file because in my opinion is the best.
Now my problem:
I want to create a folder in Internal storage to share with 2 application.
In my app, I downloaded an Apk from my server and I run it.
Before I used external storage and everything worked.
Now I want to use the internal storage for users that don't have an external storage.
I use this:
String folderPath = getFilesDir() + "Dir"
but when i try to run the Apk, it doesn't work, and I can't find this folder on my phone.
Thank you..
From this post :
Correct way:
Create a File for your desired directory (e.g., File path=new
File(getFilesDir(),"myfolder");)
Call mkdirs() on that File to create the directory if it does not exist
Create a File for the output file (e.g., File mypath=new File(path,"myfile.txt");)
Use standard Java I/O to write to that File (e.g., using new BufferedWriter(new FileWriter(mypath)))
Enjoy.
Also to create public file I use :
/**
* Context.MODE_PRIVATE will create the file (or replace a file of the same name) and make it private to your application.
* Other modes available are: MODE_APPEND, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE.
*/
public static void createInternalFile(Context theContext, String theFileName, byte[] theData, int theMode)
{
FileOutputStream fos = null;
try {
fos = theContext.openFileOutput(theFileName, theMode);
fos.write(theData);
fos.close();
} catch (FileNotFoundException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "[createInternalFile]" + e.getMessage());
}
}
Just set theMode to MODE_WORLD_WRITEABLE or MODE_WORLD_READABLE (note they are deprecated from api lvl 17).
You can also use theContext.getDir(); but note what doc says :
Retrieve, creating if needed, a new directory in which the application can place its own custom data files. You can use the returned File object to create and access files in this directory. Note that files created through a File object will only be accessible by your own application; you can only set the mode of the entire directory, not of individual files.
Best wishes.
You can create a public into a existing system public folder, there is some public folder accessible from internal storage :
public static String DIRECTORY_MUSIC = "Music";
public static String DIRECTORY_PODCASTS = "Podcasts";
public static String DIRECTORY_RINGTONES = "Ringtones";
public static String DIRECTORY_ALARMS = "Alarms";
public static String DIRECTORY_NOTIFICATIONS = "Notifications";
public static String DIRECTORY_PICTURES = "Pictures";
public static String DIRECTORY_MOVIES = "Movies";
public static String DIRECTORY_DOWNLOADS = "Download";
public static String DIRECTORY_DCIM = "DCIM";
public static String DIRECTORY_DOCUMENTS = "Documents";
To create your folder, use this code :
File myDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MyPublicFolder");
myDirectory.mkdir();
With this example, a public will be created in Documents and can be visible in any file's explorer app for Android.
try the below
File mydir = context.getDir("Newfolder", Context.MODE_PRIVATE); //Creating an internal dir;
if(!mydir.exists)
{
mydir.mkdirs();
}
This is what i have used and is working fine for me:
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(extStorageDirectory, fileName);
File parent=file.getParentFile();
if(!parent.exists()){
parent.mkdirs();
}
This will create a new directory if not already present or use the existing if already present.

Showing images outside my application using Tapestry5

I am developing my first project with Tapestry and I am about to finish, except for the images..
What do I want? I just need to display an image outside my application, example: /home/app/images/image.jpg
What did I try? I have been "googling" and reading Tapestry5 forums, I found this: http://wiki.apache.org/tapestry/Tapestry5HowToStreamAnExistingBinaryFile
I followed the steps, creating classes but I need to display the image embed on another page (so I can't use ImagePage), I tried this:
On page java class
public StreamResponse getImage() {
InputStream input = DetallesMultimedia.class
.getResourceAsStream("/home/santi/Escritorio/evolution-of-mario.jpg"); //On application, i will retrieve this from DB
return new JPEGInline(input,"hellow");
}
On page template
...
<img src="${image}" alt:image/>
...
or
...
${image}
...
Obviusly, this didn't work and I really don't know how can I do it. I read about loading the image on an event (returning the OutputStream on that event, as it's said in the HowTo linked above) but my english is so bad (I am sure you already noticed) and I don't understand well how can I do that.
Could you help me please?
Thanks you all.
I've never seen the examples as on the wiki page. Below some code on how to load an image on the classpath though using a StreamResponse.
#Inject
private ComponentResources resources;
#OnEvent(value = "GET_IMAGE_STREAM_EVENT")
private Object getProfilePic() throws Exception {
InputStream openStream = DetallesMultimedia.class.getResourceAsStream("/home/santi/Escritorio/evolution-of-mario.jpg");
byte[] imageBytes = IOUtils.toByteArray(openStream);
final ByteArrayInputStream output = new ByteArrayInputStream(imageBytes);
final StreamResponse response = new StreamResponse() {
public String getContentType() {
"image/jpegOrPngOrGif";
}
public InputStream getStream() throws IOException {
return output;
}
public void prepareResponse(Response response) {
// add response headers if you need to here
}
};
return response;
}
public String getPicUrl() throws Exception {
return resources.createFormEventLink("GET_IMAGE_STREAM_EVENT");
}
In your template:
<img src="${picUrl}"/>

Loading Image in Java Applet

When I try to run an applet in applet viewer it is not able to find resources (Image).
I try to load resource like this:
String cb= this.getCodeBase().toString();
String imgPath = cb+"com/blah/Images/a.png";
System.out.println("imgPath:"+imgPath);
java.net.URL imgURL = Applet.class.getResource(path);
but when i run it in appet viewer path is like this:
imgPath:file:D:/Work/app/build/classes/com/blah/Images/a.png
though image is there in this path,
is prefix file: causing problem, how can i test this code?
Will this code work when deployed in server and codebase returns a server URL?
Is your applet supposed to load images after it is loaded? Or would you be better served bundling necessary image resources in the jar with your applet?
I work daily on an applet-based application with plenty of graphics in the GUI.
They are bundled in the jar-file.
This si what we do:
// get the class of an object instance - any object.
// We just defined an empty one, and did everything as static.
class EmptyClass{}
Class loadClass = new EmptyClass().getClass();
// load the image and put it directly into an ImageIcon if it suits you
ImageIcon ii = new ImageIcon(loadClass.getResource("/com/blah/Images/a.png"));
// and add the ImageIcon to your JComponent or JPanel in a JLabel
aComponent.add(new JLabel(ii));
Make sure your image is actuallly in the jar where you think it is.
Use:
jar -tf <archive_file_name>
... to get a listing.
Just use /com/blah/Images/a.png as the path. getResource() is clever enough to find it.
The context classloader should work with jars.
ClassLoader cl = Thread.getContextClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("something.png"), "description");
Try this code it's only 2 methods out of the class I use to load images but it works fine for loading when using an applet.
private URL getURL(String filename) {
URL url = null;
try
{
url = this.getClass().getResource("" + extention + filename); //extention isn't needed if you are loading from the jar file normally. but I have it for loading from files deeper within my jar file like say. gameAssets/Images/
}
//catch (MalformedURLException e) { e.printStackTrace(); }
catch (Exception e) { }
return url;
}
//observerwin in this case would be an applet. Simply have the class have something like this: Applet observerwin
public void load(String filename) {
Toolkit tk = Toolkit.getDefaultToolkit();
image = tk.getImage(getURL(filename));
while(getImage().getWidth(observerwin) <= 0){loaded = false;}
double x = observerwin.getSize().width/2 - width()/2;
double y = observerwin.getSize().height/2 - height()/2;
at = AffineTransform.getTranslateInstance(x, y);
loaded = true;
}
I can post the rest of the class I use if needed

Categories