Domanda

Seen the amazing size reduction of WebP pictures (about 28% smaller than "pngcrushed" PNG for lossless + alpha pictures), we'd like to serve WebP pictures to browsers supporting WebP.

How can I detect from a Java webapp server if the client's browser is supporting WebP?

There's been a question here about how to do it from JavaScript:

Detecting WebP support

But I'd like to know how to do it from Java. If doing from Java means calling JavaScript on the client side then I'd like to know how to to that.

È stato utile?

Soluzione

You can't determine web browser features using Java alone. Java/JSP runs in webserver, not in webbrowser. You really need to use JavaScript for this. You can use the code for this which you already found on the related question. Easiest what you can do, is to let JS check on page load if there isn't already some cookie present indicating that the browser supports WebP and then do the feature detection accordingly and finally set a long living cookie by document.cookie and reload the page by location.reload().

In the server side, you'd just have to check for the presence of the cookie and/or its value by HttpServletRequest#getCookies() in servlet or ${cookie} in JSP before sending/setting the appropriate image URL.

Other than setting a cookie, you can always let JS to send the data as request parameters of an ajax request, but this means that you have to do it on every request or session.

Altri suggerimenti

There is a simple way of detecting webP support on the client. You could then set a cookie on the client and read the value on the server.

function testWepP(callback) {
   var webP = new Image();     
   webP.src = 'data:image/webp;base64,UklGRi4AAABXRUJQVlA4TCEAAAAvAUAAEB8wAiMw' + 
'AgSSNtse/cXjxyCCmrYNWPwmHRH9jwMA';
   webP.onload = webP.onerror = function () {
      callback(webP.height === 2);     
   }; 
};

testWebP(function(supported) {
   console.log((supported) ? "webP 0.2.0 supported!" : "webP not supported."); 
});

More information here.

The answers above seem kinda old? Looks like you can check the Accept header to see if it contains the webp string...

   public boolean hasWebPSupport(HttpServletRequest req) {
        return req.getHeader("Accept").contains("image/webp");
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top