libgdx GWT. Create Texture from url - java

I need help.
I need display jpg image from url.
Desktop version work fine
byte[] imgBytes
new Pixmap(imgBytes, 0, imgBytes.length)
But it is not work in GWT project.
I try this solution "Tainted canvases may not be loaded" Cross domain issue with WebGL textures
public void downloadPixmap(final String url, final DownloadPixmapResponse response) {
final RootPanel root = RootPanel.get("embed-html");
final Image img = new Image(url);
img.getElement().setAttribute("crossOrigin", "anonymous");
img.addLoadHandler(new LoadHandler() {
#Override
public void onLoad(LoadEvent event) {
HtmlLauncher.application.getPreloader().images.put(url, ImageElement.as(img.getElement()));
response.downloadComplete(new Pixmap(Gdx.files.internal(url)));
root.remove(img);
}
});
root.add(img);
}
interface DownloadPixmapResponse {
void downloadComplete(Pixmap pixmap);
void downloadFailed(Throwable e);
}
but it is work only in Chrome browser. It is not work in Mozilla Firefox.
Help me please

Problem was in url. Some url do not have header
Access-Control-Allow-Origin *
That is why images do not display. I fix this using nginx.
Here link to my settings, my problems and ansvers
https://serverfault.com/questions/816080/nginx-proxy-pass-regexp-to-another-domain

Related

Load image from URL and default image on error

I am trying to load an image from a URL and this was very easy and works great. However, if the image doesnt exist I want it to default to a local image. The problem I am having is that it doesnt throw any exceptions. Instead it will just not display anything. I'm assuming I have to validate the URL some how, but I want to also be sure that its an image and not a webpage/script...etc
Here is my basic test code. This works:
public class DownloadImage extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
VBox root = new VBox();
String imageSource = "https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png";
ImageView imageView = new ImageView(new Image(imageSource));
root.getChildren().add(imageView);
primaryStage.setScene(new Scene(root, 1000, 1000));
primaryStage.show();
}
}
But if I load a bad URL i.e. (two s's in Portals):
String imageSource = "https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png";
It will just be blank. I thought about creating an HTTP client and sending a request prior to creating the image, but generating the HTTP client takes a few seconds and I will be loading upwards of 300 or so images. I guess I can have one http client, and make one request for each image and check the response datatype to see if its an image, but is there a better way?
You can use the errorProperty and exceptionProperty to check the error status of the image:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.image.Image;
import javafx.stage.Stage;
public class ImageTest extends Application {
public static void main(String[] args) {
launch(args) ;
}
#Override
public void start(Stage primaryStage) {
String[] urls = new String[]{
"https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png",
"https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png"
} ;
for (String url : urls) {
Image image = new Image(url);
if (image.isError()) {
System.out.println("Error loading image from "+url);
// if you need more details
// image.getException().printStackTrace();
} else {
System.out.println("Successfully loaded image from " + url);
}
}
Platform.exit();
}
}
Which gives the following output:
Successfully loaded image from https://www.wbkidsgo.com/Portals/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png
Error loading image from https://www.wbkidsgo.com/Portalss/1/Content/Hero/HeroBugsCarrot/Source/Default/WB_LT_HeroImage_Bugs_v1.png
You can use the ImageView.setImage() method to change the image. I recommend initializing the ImageView using your default image in the form of a BufferedImage, then setting it later with your actual image. You can load this from your filesystem or classpath using ImageIO.
As for the actual image, I would also use ImageIO to load the url as a BufferedImage. This throws an IOException, so if it errors or does not link to a supported image type, nothing will happen.
If you know much about threads and concurrency, I would load the image on another thread so it doesn't freeze your main thread.

Wicket create image from file system outside web application directory

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;
}
}));

Blackberry permissions to connect internet after signing?

While working with Browser Field in Blackberry the code is working when running in simulator before signing. But after signing app is not working, means webpage is not loading.. code is as follows...
code:
public final class MyScreen extends MainScreen
{
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
ButtonField bf = new ButtonField("google");
bf.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
Dialog.alert("this is button click");
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
BrowserField browserField = new BrowserField();
add(browserField);
browserField.requestContent("http://www.google.com");
}
}, 2000, false);
}
});
add(bf);
}
}
As per the following code, if i am executing it in simulator before signing working good & website is loading. But after signing my app with signing keys and if i am executing in device, it is not executing means website is not loading, just blank page is displaying.
Not getting what is the problem with my app before & after signing.
After searching in internet, got some information that we need to pass some suffixes to work after signing, in devices when using HTTPconnections like
HttpConnection httpConn;
StreamConnection s;
String url;
s = (StreamConnection)Connector.open(url+";deviceside=true");
But if i am passing the same code in browser field means it is concatenating with the given url like..
browserField.requestContent("http://www.google.com" + ";deviceside=true");
and getting error like unable to find "http://www.google.com;deviceside=true"
so, can anyone please suggest me how to access internet using browser field after blackberry applications are signed.
My app needs to support OS 6.0 & 7.0
try this code -
String url="http://www.google.com";
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE,BrowserFieldConfig.NAVIGATION_MODE_POINTER);
browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent(url);

download file from database through browser in java desktop (non web)

is it possible to download file from database through browser (ex: mozilla,chrome) in java desktop application (non web app) ? can you explain me with an example code ?
thanks in advance,
Use Desktop#browse() wherein you just specify the URI of that file (exactly the one as you would enter in the address bar of a normal webbrowser).
Desktop.getDesktop().browse(new URI("http://example.com/download/file.ext"));
The other side has just to set Content-Disposition: attachment on this response to force a Save As dialogue (and of course fill the response body with the necessary data from the DB).
Anything that is available through a browser should be available to a Java desktop app. At least unless the server (e.g. Google) goes to measures to block 'programmatic access'.
can you explain me with an example code?
Sure, adapted from the Java Sound info. page.
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
public class LoopSound {
public static void main(String[] args) throws Exception {
// imagine a DB is preparing/serving this - same difference.
URL url = new URL(
"http://pscode.org/media/leftright.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(-1);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}

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}"/>

Categories