Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

php - detect retina (HD) display on the server side

I found many questions about Retina Display, but none of the answers were on the server side.

I would like to deliver a different image according to the screen, ex (in PHP):

if( $is_retina)
    $thumbnail = get_image( $item_photo, 'thumbnail_retina' ) ;
else
    $thumbnail = get_image( $item_photo, 'thumbnail' ) ;

Can you see a way of dealing with this?

I can only imagine a test in JavaScript, setting a Cookie. However this requires an initial exchange to set it. Anyone have a better solution?

Cookie setting code:

(function(){
  if( document.cookie.indexOf('device_pixel_ratio') == -1
      && 'devicePixelRatio' in window
      && window.devicePixelRatio == 2 ){

    document.cookie = 'device_pixel_ratio=' + window.devicePixelRatio + ';';
    window.location.reload();
  }
})();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Alright since it seems there's no better way for the moment, here is my solution combining JS, PHP and Cookies.

I hope there will be better answers in the future

<?php
    if( isset($_COOKIE["device_pixel_ratio"]) ){
        $is_retina = ( $_COOKIE["device_pixel_ratio"] >= 2 );

        if( $is_retina)
            $thumbnail = get_image( $item_photo, 'thumbnail_retina' ) ;
        else
            $thumbnail = get_image( $item_photo, 'thumbnail' ) ;

    }else{
?>
<script language="javascript">
(function(){
  if( document.cookie.indexOf('device_pixel_ratio') == -1
      && 'devicePixelRatio' in window
      && window.devicePixelRatio == 2 ){

    var date = new Date();
    date.setTime( date.getTime() + 3600000 );

    document.cookie = 'device_pixel_ratio=' + window.devicePixelRatio + ';' +  ' expires=' + date.toUTCString() +'; path=/';
    //if cookies are not blocked, reload the page
    if(document.cookie.indexOf('device_pixel_ratio') != -1) {
        window.location.reload();
    }
  }
})();
</script>
<?php } ?>

in function.php :

add_action( 'init', 'CJG_retina' );

function CJG_retina(){

    global $is_retina;  
    $is_retina = isset( $_COOKIE["device_pixel_ratio"] ) AND $_COOKIE["device_pixel_ratio"] >= 2;
}

Then after I can use the following GLOBAL:

global $is_retina; or $GLOBALS['is_retina'];


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...