not-an-aardvark / snoowrap

A JavaScript wrapper for the reddit API
MIT License
1.02k stars 127 forks source link

Get gallery images #328

Open greynguyen opened 3 years ago

greynguyen commented 3 years ago

It seems like with PRAW we can get images in galleries using media_metadata. Is there a way to do the same with snoowrap?

Raphiel-Ainsworth commented 3 years ago

For anyone trying to work this out, the way I'm doing this at the moment is to grab the image reference code(s), and build a path to the image(s) I'm targeting with help from the following function;

// Returns a dot notation address from a built string.
function ref(obj, str) {
    return str.split(".").reduce(function (o, x) { return o[x] }, obj);
}

Example below, but note that for my app I'm only grabbing the first gallery image in order to display a post preview, and I'm also targeting the array of preview images (the lower resolution images that get generated by Reddit) as opposed to the source image, as the resolution / filesizes of the source images can be overkill for what I'm using them for.

It shouldn't be too tricky to adapt the code to loop over the gallery_data.items array and grab all source images (by building directly to the source url (.s.u) instead of one of the preview images (.p.u)), if that's what you wanted. View the data structure of the Reddit post to see what's available.

Obviously once you have the URL of the images, you can download or do what you want with them.

// If the post we are dealing with is a gallery
// [...]

// Grab the image reference code of the first gallery image
var imageRef = item.gallery_data.items[0].media_id;

// Build a path to the array of preview images;
var path = 'media_metadata.' + imageRef + '.p';

// Covert the path string to dot notation address
var previewArray = ref(item, path);

// Get URL of the largest preview image available
var imageURL = previewArray[previewArray.length - 1].u;