I am using Primefaces p:graphicImage to display the image of every logged in users. Everything is working near fine except that my photos appear like negatives. What could I be doing wrong. Here is my code :
<sec:authorize access="isAuthenticated()">
<span>
<p:graphicImage value="#{currentUser.image}" class="img-thumbnail pull-right"
height="80px;" width="80px;" >
<f:param name="id" value="#{request.remoteUser}" />
</p:graphicImage>
</span>
.....
And here is the JSF Managed Bean
#Named(value = "currentUser")
#ApplicationScoped
public class CurrentUser implements Serializable {
#EJB
private VempDetailsFacade vempDetailsFacade;
private VempDetails details;
public StreamedContent getImage() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
// So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
return new DefaultStreamedContent();
} else {
// So, browser is requesting the image. Return a real StreamedContent with the image bytes.
String imageId = context.getExternalContext().getRequestParameterMap().get("id");
details = vempDetailsFacade.find(imageId);
if (details != null) {
try {
return new DefaultStreamedContent(new ByteArrayInputStream(details.getEmpImage()));
} catch (Exception e) {
System.err.println("No Image Retrieved : "+e.getMessage());
}
}
return null;
}
}
public VempDetails getDetails() {
return details;
}
public void setDetails(VempDetails details) {
this.details = details;
}
#PostConstruct
public void init() {
details = vempDetailsFacade.
find(FacesContext.getCurrentInstance().getExternalContext().getRemoteUser());
}
}
What is it I could be doing wrong. The same pictures displayed in a normal swing application display without any problem
Update On Code
#BalusC
Here is the quick test code that displays the image on swing.
public DisplayImage() {
super("Image Display");
setSize(600, 600);
connection = getConnection();
try {
statement = connection
.prepareStatement("SELECT empImage FROM v_empDetails WHERE empCode=?");
statement.setString(1, "009");
result = statement.executeQuery();
byte[] image = null;
//just a result anyway
while (result.next()) {
image = result.getBytes(1);
}
Image img = Toolkit.getDefaultToolkit().createImage(image);
ImageIcon icon = new ImageIcon(img);
JLabel lPhoto = new JLabel();
lPhoto.setIcon(icon);
add(lPhoto);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setVisible(true);
}
public Connection getConnection() {
Connection connection = null;
........
Could it be that the Toolkit.getDefaultToolkit().createImage(image); line is doing the re-invert. The images were populated using a different application and this is more of an update to have it as a web-based application.
Thanks for your advice in advance.
JSF/PrimeFaces is just the presenter and doesn't invert the images at all. Otherwise anyone else in the world using JSF/PrimeFaces would have faced the same problem. Your problem lies deeper. It's more likely that the images are already stored as negatives in DB and that your existing Swing/Java2D code is written in such way that it re-inverts the images before displaying, perhaps during a badly written resizing/cropping process.
So, to fix the problem, refocus on the code responsible for storing those images in the DB (and don't forget to fix the Swing/Java2D code to not re-invert those anymore).
Related
I am using external images in my webaplication, everything wass fine until I wanted to add animated gif there, the gif loads, but it doesn't animate.
Java code:
File sourceimage = new File("loading_img.gif");
try {
final BufferedDynamicImageResource r = new BufferedDynamicImageResource("GIF");
r.setImage(ImageIO.read(sourceimage));
add(new Image("gif", r));
} catch (Exception e) {
e.printStackTrace();
}
HTML:
<img wicket:id="gif"/>
EDIT:
Tried martin-g suggestion, gif still doesn't animate
try {
final BufferedDynamicImageResource r = new BufferedDynamicImageResource("GIF"){
#Override
protected void setResponseHeaders(AbstractResource.ResourceResponse data,
IResource.Attributes attributes){
super.setResponseHeaders(data, attributes);
data.setContentType("image/gif");
}
};
r.setImage(ImageIO.read(sourceimage));
add(new Image("gif", r));
} catch (Exception e) {
e.printStackTrace();
}
The problem is that the content type is not automatically set.
You will need to override org.apache.wicket.request.resource.AbstractResource#setResponseHeaders() and set with via resourceResponse.setContentType(String).
Maybe this should be done automatically by Wicket in org.apache.wicket.request.resource.DynamicImageResource, since it knows the format ("png", or "gif" as in your case). Please file a ticket in Wicket's JIRA for this improvement! Thanks!
I've wrote a bean that takes photos from a webcam. I'd like to display these image in a JSF 2.0 page and update them every n second.
If I give the path name the file in eclipse like this it work:
public String getNewPhoto() {
try {
File dir = new File("C:/Users/User/MyApp/images/");
FileUtils.cleanDirectory(dir);
}catch(Exception ex) {
ex.printStackTrace();
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
try {
webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("C:/Users/User/MyApp/images/"+ timeStamp + ".png"));
webcam.close();
}catch(Exception ex) {
ex.printStackTrace();
}
return "C:/Users/User/MyApp/images/" + timeStamp + ".png";
}
With the following XHTML:
<p:graphicImage value="#{myBean.newPhoto}" id="photo" cache="false" />
<p:poll interval="1" listener="#{myBean.increment}" update="photo" />
As expect all of the above works fine from my dev environment on eclipse. I'd like to deploy this to my server (Linux). When I change the paths from what you see above to
/var/lib/tomcat7/webapps/MyApp/images
Then the images get saved, but I can't display them in h:graphicImage. I also tried passing:
http://hostname:8080/MyApp/images/....
to h:graphicImage and still no dice, I'm sure I'm missing something real simple. Any help is appreciated!
You need to change it in the image saving line as well . . .
ImageIO.write(webcam.getImage(), "PNG", new File("C:/Users/User/MyApp/images/"+ timeStamp + ".png"));
How about the following:
View
<p:graphicImage value="#{photoBean.newPhoto}" id="photo" cache="false" />
<p:poll listener="#{photoBean.updatePhoto}" interval="1"
update="photo" />
Managed Bean
#ManagedBean
#RequestScoped
public class PhotoBean {
private String realPath;
private String realtivePath;
#PostConstruct
public void init() {
realtivePath = "/images/webcam.png";
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
realPath = externalContext.getRealPath(realtivePath);
}
public void updatePhoto() {
try {
File file = new File(realPath);
file.delete(); // cleanup
// Use file object to write image...
} catch (IOException e) {
// Implement some exception handling here
e.printStackTrace();
}
}
public String getNewPhoto() {
return realtivePath;
}
}
Some more notes (getters)
It's not a good idea to process the webcam image in the getter (getNewPhoto) as getters may be called multiple times by JSF.
See: Why JSF calls getters multiple times
Timestamp
I've removed the timestamp from the filename. I think you've added it to prevent browser caching. This is not required as cache=false already creates unique image URIs.
I'm now trying to learn Oracle ADF and I'm getting a NullPointerException while running the following code on a Java bean.
Can you help me figure out what I'm doing wrong please? This is being invoked from a button on a JSPX page.
public String cb1_action() {
try{
BindingContext bindingctx = BindingContext.getCurrent();
BindingContainer bindings = bindingctx.getCurrentBindingsEntry();
DCBindingContainer bindingsImpl = (DCBindingContainer)bindings;
DCIteratorBinding iter = bindingsImpl.findIteratorBinding("ViewObj1Iterator");
Row row = iter.getCurrentRow();
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste");
}
catch(Exception e) {
System.out.println("Excepcao em: ");
e.printStackTrace();
}
return null;
}
According to the Stack trace, the error occurs on the first row.setAttribute() line.
Also, I'm using the latest version of JDeveloper with the integrated WebLogic server.
Best regards,
Pedro
Row row = iter.getCurrentRow();
if(row != null){
row.setAttribute("Id", 123);
row.setAttribute("Nome", "Pedro Teste"); //name?
}
The info that you get the error at
row.setAttribute("Id", 123);
let me think that you try to alter the primary key attribute of the row, which is not allowed. Not sure about this as you did not mention the error you get.
Ok, so here's how I figured out how to get around this:
First, I asked jDeveloper to generate a class for the Application Module.
In that class, I added the following methods:
public void testEntityObject()
{
System.out.println("Let's try our Entity Object...");
try
{
EntityDefImpl entity = TesteEOImpl.getDefinitionObject();
TesteEOImpl ti = (TesteEOImpl)entity.createInstance2(getDBTransaction(), null);
ti.setId(new BigDecimal(123));
ti.setNome("Entity Object test...");
getDBTransaction().commit();
System.out.println("Looks good :-)");
}
catch(Exception e)
{
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
public void testViewObject() {
System.out.println("Let's try our View Object...");
ViewObjectImpl vo = this.getTeste1();
try{
Row row = vo.createRow();
row.setAttribute("Id", 234);
row.setAttribute("Nome", "VO test");
vo.insertRow(row);
getDBTransaction().commit();
System.out.println("Looks good :-)")
}
catch(Exception e) {
System.out.println("It seems something went wrong :-(");
e.printStackTrace();
}
}
These methods are being called by a managed bean that is connected to two buttons on the page. This managed bean has the following methods. I'll post just one of them as only the method names change:
public String cb1_action() {
try{
FacesContext fctx = FacesContext.getCurrentInstance();
BindingContext bindingContext = BindingContext.getCurrent();
DCDataControl dc = bindingContext.findDataControl("AppModuleAMDataControl");
AppModuleAMImpl am = (AppModuleAMImpl)dc.getDataProvider();
am.criarTesteComEntityObject();
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
I know this is not rocket science or anything but it took a while for me to get there...
Basically, your answers helped me a lot to go and investigate what was happening. The cause? Poor design! ADF is supposed to be organized...
Thank you everyone! :D
My Problem... I have accessed the Camera App from my third party app , I then take a picture. then I go to the Menu and I have added in a menuitem (MENUITEM_CAMERA_PREVIEW) . My menu item must perform a function and once it has I want my app to close the camera and open the previose screen before the Camera app was opened.
I am facing the same problems as this thread :
http://supportforums.blackberry.com/t5/Java-Development/How-to-exit-camera-app-properly/m-p/1924127#M209092
Can someone please tell me they understand the solution, if not and you maybe know the solution your help would be much appreciated.
I have seen these post:
Closing the default camera in Blackberry programatically after taking a picture
http://supportforums.blackberry.com/t5/Java-Development/Unable-to-close-camera-using-EventInjector-for-touch-screen/m-p/785247#M143879
How to exit a blackberry application from another application programatically?
But I am not sure what I am supposed to add to exit the camera application from my third party application.
Can Someone Please help me understand....
Trying to close the Camera app from your app is tricky. I don't know of a clean way to do it, but I have done it this way.
Basically, your app needs to request permission
ApplicationPermissions.PERMISSION_INPUT_SIMULATION
to inject keystrokes. It will then simulate the pressing of the ESC key, which is how a user would/could close the Camera app manually. To make this technique more reliable, I need to have the code (conditionally) inject the ESC key multiple times.
The way I make this more reliable is that I have a Screen in my app that is showing, before I launch the Camera app. I then monitor that screen to see when it has been exposed again. When I detect that it has been exposed, I assume that I must have injected enough ESC key sequences to close the Camera (or I guess the user could have pressed ESC themselves, to get back to my app).
Update: per comment below, here is some additional code I used in this solution, to detect proper Camera closure by monitoring the exposed state of one of my Screens below it:
private boolean _isExposed = false;
protected void onExposed() {
super.onExposed();
_isExposed = true;
}
protected void onObscured() {
super.onObscured();
_isExposed = false;
}
public boolean isExposed() {
return _isExposed;
}
You can also set _isExposed to false in whatever method you use to open the Camera app in the first place, if you like.
This is the code I ended up using, its much better.
public class MyScreen extends MainScreen{
Player _p;
VideoControl _videoControl;
FileConnection fileconn;
String PATH;
String GetfileName;
LabelField GetPhotofileName = new LabelField("",LabelField.FOCUSABLE){
protected boolean navigationClick(int status, int time){
Dialog.alert("Clicked");
return true;
}
};
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
} else {
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
byte[] rawImage = _videoControl.getSnapshot(null);
fileconn=(FileConnection)Connector.open(PATH);
if(fileconn.exists()){
fileconn.delete();
}
fileconn.create();
OutputStream os=fileconn.openOutputStream();
os.write(rawImage);
GetfileName =fileconn.getName();
fileconn.close();
os.close();
Status.show("Image is Captured",200);
GetPhotofileName.setText(GetfileName);
if(_p!=null)
_p.close();
}catch(Exception e){
if(_p!=null){
_p.close();
}
if(fileconn!=null){
try{
fileconn.close();
}catch (IOException e1){
}
}
}
}
}
return handled;
}
public MyScreen(){
setTitle("Camera App");
try{
_p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
_p.realize();
_videoControl = (VideoControl) _p.getControl("VideoControl");
if (_videoControl != null){
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
_videoControl.setVisible(true);
_p.start();
if(videoField != null){
add(videoField);
}
}
}catch(Exception e){
if(_p!=null) {
_p.close();
}
Dialog.alert(e.toString());
}
add(GetPhotofileName);
}
}
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}"/>