Showing an image in an image viewer

Showing an image in an image viewer

Loren MaxwellLoren Maxwell Posts: 382Questions: 93Answers: 10
edited January 2022 in DataTables 1.10

Just sharing this for anyone interested.

I wanted to show a thumbnail in a table that would expand to full size in an image viewer when clicked on.

There are several image viewer packages out there, but I settled on Viewer.js for no particular reason other than the mouse wheel is used to zoom in/out, which I found more intuitive than other uses for the mouse wheel that other image viewers had (i.e., scroll up/down on the image or cycle through a set of images, etc.).

Viewer.js:
Home page -- https://fengyuanchen.github.io/viewerjs/
Github -- https://github.com/fengyuanchen/viewerjs

There's also a jQuery plugin wrapper for it:
Home page -- https://fengyuanchen.github.io/jquery-viewer/
Github -- https://github.com/fengyuanchen/jquery-viewer

After including Viewer.js and the jQuery plugin wrapper, here's the code for the image column (a thumbnail):

columns: [{
    ....
}, {
    title: "Image",
    data: "file_id",
    defaultContent: "No image",
    render: function(d, t, r) {
        return d ?
            "<img src=" + r.web_path_thumb_sm + " alt=" + r.file_name + ">" :
            null
    },
    className: "image"
}, {
    ....
}],

There's nothing really different than the examples on this site of how to include an image in a table, but notice the "image" class added (although it could be anything).

Finally, here's my function to show the full size image in the image viewer when the thumbnail in the table is clicked:

table.on("click", "td.image", function(e) {
    e.preventDefault()

    let table = $(this).closest("table").DataTable()
    let row = $(this).closest("tr")
    let data = table.row(row).data()

    let image = new Image()
    image.src = data.web_path
    image.alt = data.file_name

    let viewer = new Viewer(image, {
        zoomRatio: 2,
        maxZoomRatio: 2,
        hidden: function() {
            viewer.destroy();
        }
    }).show()
})

This code is based on this example:
https://fengyuanchen.github.io/viewerjs/examples/dynamic-viewer.html

Note that the src for the table above is "web_path_thumb_sm", which shows a thumbnail in the table itself, while the src for the viewer is "web_path", which shows the full size image.

Anyway, when the cell with the "image" class is clicked, the image viewer will show and the image itself can then be viewed in more detail. Also when the viewer is closed (hidden) the viewer itself is destroyed.

Anyway, I'm fairly pleased with the results -- I hope this is helpful to anyone who wants to do the same!

Replies

  • allanallan Posts: 61,453Questions: 1Answers: 10,055 Site admin

    Very nice - thanks for sharing this with us!

    Allan

Sign In or Register to comment.