解決:使用Photoswipe進行圖片展示

python 2.7
Django 1.6.1
photoswipe


前言

對於前端的照片存儲,已經在前一篇博文中進行展示,使用的是dropzone.js的包,圖片存儲的作用就是爲了數據的再調用,所以在此片進行上次圖片的前端展示,因爲我是個前端萌新,所以方法比較稚嫩,希望觀衆老爺不要嘲笑,多多指教咯。

如何上傳圖片並保存請看:dropzone拖拽圖片上傳並保存到本地


樣式的選擇和調試請參考這裏,非常好用—photoswipe教程事例

html

<!-- 開闢圖片展示空間 -->
<div class="my-gallery" itemscope id="img_show" style="overflow-x: hidden;height:290px;"></div>

<!-- 引入js包和css樣式 -->
<script type="text/javascript" src="/media/PhotoSwipe-master/dist/photoswipe.min.js"></script>
<script src="/media/PhotoSwipe-master/dist/photoswipe-ui-default.min.js"></script>
<link rel="stylesheet" href="/media/PhotoSwipe-master/dist/photoswipe.css">
<link rel="stylesheet" href="/media/PhotoSwipe-master/dist/default-skin/default-skin.css">


<!-- 官方教程中的代碼 -->
<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element, as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
        <!-- don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

          </div>

        </div>
</div>

//根據官方教程,這裏的style不管寫在哪都可以調用,因爲class名字比較獨特吧
<style>
  .my-gallery {
  width: 100%;
  float: left;
}
.my-gallery img {
  width: 100%;
  height: auto;
}
.my-gallery figure {
  display: block;
  float: left;
  margin: 0 5px 5px 0;
  width: 150px;
}
.my-gallery figcaption {
  display: none;
}
</style>

javascript

<script>
//官方的其中一種樣式
var initPhotoSwipeFromDOM = function(gallerySelector) {
    // parse slide data (url, title, size ...) from DOM elements 
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
            numNodes = thumbElements.length,
            items = [],
            figureEl,
            linkEl,
            size,
            item;

        for(var i = 0; i < numNodes; i++) {

            figureEl = thumbElements[i]; // <figure> element

            // include only element nodes 
            if(figureEl.nodeType !== 1) {
                continue;
            }

            linkEl = figureEl.children[0]; // <a> element

            size = linkEl.getAttribute('data-size').split('x');

            // create slide object
            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };



            if(figureEl.children.length > 1) {
                // <figcaption> content
                item.title = figureEl.children[1].innerHTML; 
            }

            if(linkEl.children.length > 0) {
                // <img> thumbnail element, retrieving thumbnail url
                item.msrc = linkEl.children[0].getAttribute('src');
            } 

            item.el = figureEl; // save link to element for getThumbBoundsFn
            items.push(item);
        }

        return items;
    };

    // find nearest parent element
    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };

    // triggers when user clicks on thumbnail
    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        // find root element of slide
        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }

        // find index of clicked item by looping through all child nodes
        // alternatively, you may define index via data- attribute
        var clickedGallery = clickedListItem.parentNode,
            childNodes = clickedListItem.parentNode.childNodes,
            numChildNodes = childNodes.length,
            nodeIndex = 0,
            index;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) { 
                continue; 
            }

            if(childNodes[i] === clickedListItem) {
                index = nodeIndex;
                break;
            }
            nodeIndex++;
        }



        if(index >= 0) {
            // open PhotoSwipe if valid index found
            openPhotoSwipe( index, clickedGallery );
        }
        return false;
    };

    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
        params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');  
            if(pair.length < 2) {
                continue;
            }           
            params[pair[0]] = pair[1];
        }

        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }

        return params;
    };

    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;

        items = parseThumbnailElements(galleryElement);

        // define options (if needed)
        options = {

            // define gallery index (for URL)
            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(index) {
                // See Options -> getThumbBoundsFn section of documentation for more info
                var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                    pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                    rect = thumbnail.getBoundingClientRect(); 

                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            }

        };

        // PhotoSwipe opened from URL
        if(fromURL) {
            if(options.galleryPIDs) {
                // parse real index when custom PIDs are used 
                // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
                for(var j = 0; j < items.length; j++) {
                    if(items[j].pid == index) {
                        options.index = j;
                        break;
                    }
                }
            } else {
                // in URL indexes start from 1
                options.index = parseInt(index, 10) - 1;
            }
        } else {
            options.index = parseInt(index, 10);
        }

        // exit if index not found
        if( isNaN(options.index) ) {
            return;
        }

        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }

        // Pass data to PhotoSwipe and initialize it
        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };

    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );

    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
        openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
};

// execute above function
initPhotoSwipeFromDOM('.my-gallery');


//這裏開始是自己需要寫的代碼,頁面一開始就進行加載
window.onload=img_result();
function img_result(){
  var loc = location.href;
  var n1 = loc.length;//地址的總長度
  var n2 = loc.indexOf("=");//取得=號的位置
  var order_id = decodeURI(loc.substr(n2+1, n1-n2));//從=號後面的內容     
  console.log("執行了2");
  //根據url寫的映射,進入enter這個app然後調用get_case3這個函數進行處理

    $.get('/enter/get_case3/',
                {
                    //前臺獲取order_id傳入後臺當做參數
                    'order_id':order_id,
                },
                //從view.py中的方法可知,產生的data形式是一個list,list元素是dict,裏面藏着對應dui'y'n該編號下的圖片路徑
               function(data){  

                    if(data[0]==""){
                        console.log("爲空")

                    }
                    else{
                    var j=0
                    // console.log("dropzone")
                    var html_string='';
                    var aa = data.length;
                    console.log(aa);
                    for(var i=0;i<data.length;i++){
                      // 獲取存在服務器本地文件夾中的圖片路徑
                      var newimg = '/media/'+data[i]["img"]
                      console.log(newimg)
                      html_string+='<figure itemprop="associatedMedia" style="height:200px"><a href="'+newimg+'" itemprop="contentUrl" data-size="640x1136" ><img src="'+newimg+'" itemprop="thumbnail" alt="Image description" id="img1_1"/></a><figcaption itemprop="caption description"></figcaption></figure>';
                      j=j+1;
                     }    
                    //比較弱的方法,就是構造html的字符串組,然後添加到id爲img_show的空間中
                    $("#img_show").append(html_string);

                  }
                },
      'json' ); 
</script>

urls.py

這裏構成的是一種前端映射到view的函數比如說,網頁的後綴變成了get_case3了,映射的處理的函數指的就是後面的get_case3(完全可以寫的不一樣,只要找對映射關係就可以了)


urlpatterns = patterns('enter.views',

    url(r"^get_case3/","get_case3"),

)

view.py

def get_case3(request):
  order_id = request.GET.get("order_id","")
  conn= MySQLdb.connect(
          host=你的host主機,
          port = 端口號,
          user='root',
          passwd=密碼,
          db =數據庫名字,
    )
  cur = conn.cursor()
  conn.set_character_set('utf8')
  cur.execute('SET NAMES utf8;')
  cur.execute('SET CHARACTER SET utf8;')
  cur.execute('SET character_set_connection=utf8;')
  # 選擇出標號對應的所需要的圖
  cur.execute("select img from  enter_img where order_id='"+order_id+"'")
  server_info_advance=cur.fetchall()
  advance_info2=[]
  for data3 in server_info_advance:
    dict_result={}
    dict_result["img"]=data3[0]
    advance_info2.append(dict_result)
  advance_info3=[]
  if len(advance_info2)<100: # 
    return advance_info2
  else:
    return  advance_info3

model的表現形式

# 數據庫名字叫做enter_img
+-----+----------+-------------------------------------+
| id  | order_id | img                                 |
+-----+----------+-------------------------------------+
| 460 | 1234     | upload/1491036872.27WechatIMG2.png  |
+-----+----------+-------------------------------------+

這裏回顧下過程,整個流程在於在前端觸發一個帶返回的id號,之後將這個id號代入後臺進行數據庫的索引,之後再從後臺構造好傳遞到前端,前端在進行圖片展示,photoswipe這個js包的作用就是完成圖片比較酷炫展示的作用,其中要注意的是圖片尺寸的選擇,後續有空需要把自動獲取尺寸的代碼構造出來,目前如果不是非本分辨率的圖片,放大後將呈現出很差的體驗效果,後續可能會對圖片上傳時,對圖片尺寸的進行獲取和存值,這樣再進行調出的時候,效果就會好很多。–來自自學前端三個禮拜的小白的心聲


Pay Attention

  • 關於id的傳入,這裏用的方法非常的樸素,應該是從一個頁面點擊該id然後獲取該id下的明細,也就是涉及到頁面跳轉的概念了,然後再將id傳遞進入後臺,再操作

Update

可以參考這裏,直接把包導出即可進行本地調試

步驟:右下角export-export.zip ,然後下載到本地愉快的雙擊index.html即可


最後

關於爲啥我把上傳圖片和展示圖片分成兩篇來寫,,,,,因爲,,我懶啊,哈哈哈哈,不鬧,片段剝離,有利於重複利用,嗯,就是醬紫


後續

解決問題畢竟還是需要進行復盤和記錄,這樣對以後的發展和回顧有非常大的益處,構造方法上的選擇需要接軌目前主要的方法,對於前後臺脫離的團隊,需要進行標準的數據傳輸,前端妹子們可不管後臺怎麼構造方法,她們只要進行前端頁面展示就可以了(然而ui,美工,後臺都tm是我寫0.0),後續等我有空閒下來的時間,把整個構建構建工程和app的過程都仔細寫一下,從整個項目中剝離出來讓純正小白也可以一下子學會,目前只能當爲自己的學習筆記,如果思想對你有所幫助,我也很高興。共勉

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章