Jekyll: Get width/height of an image without using an external plugin - ruby

I want to automatically add height and width attributes to all my images. It is perfectly done via this nice plugin, but I host my site on GitHub Pages where external plugins are not supported.
Question: How to prefill height/width attributes of an image without using a plugin?
Why do I need this?
My site works well even without height and width but I want to specify them because it is important from SEO point of view (you can find some details on its importance here).

Writing an internal filter to do this using the fastimage gem is fairly simple. You can define your filter in the _plugins directory of your project (this is outlined in the Jekyll documentation)
As a very rough example, you could do something like this:
require 'fastimage'
module ImageSizeFilter
def image_size(source, dimension = nil)
# Get the image dimensions, throw an error on failure
# NOTE: You may want to sanitize the input string provided here
# see: https://github.com/sdsykes/fastimage#security
size = FastImage.size(source, raise_on_failure: true)
# Return the requested dimension, or both dimensions if nothing was specified
return size[0] if dimension == 'w'
return size[1] if dimension == 'h'
return size unless dimension
# Fail if the requested dimension is invalid
raise 'Invalid image size dimension requested: ' + dimension
end
end
Liquid::Template.register_filter(ImageSizeFilter)
Which would be used like so:
<img src={{source}}
width="{{source | image_size: 'w'}}"
height="{{source | image_size: 'h'}}"/>
Of course this still won't work with GitHub pages directly because custom plugins are not supported. To use custom plugins in general, one solution is to build the site locally and include it in the repository.

This question seems to apply to content images in markdown files. These images have no width or height set by default.
The short answer
You can just set the width and height directly in HTML in your markdown, like this:
# Markdown title
paragraph
<img src="/path/to/image.jpg" width="400" height="300" />
The long answer
You cannot retreive the width and height of the image programmatically without a plugin, so when you use (pure) markdown you get an image without a width and height property. The question is WHY you wanted to add a width and a height in the first place. Setting the width and height prevents reflow, but it leaves a big gaping hole while loading. Is that truly better? It certainly does not look nice. Progressive JPG's are a very nice solution for this problem, but I do not prefer to set the width and height on them, as 'no image' looks good, and a progressive JPG also always looks good.
You say you want it for SEO reasons, but I cannot think of any.
If your website is so slow you actually want to interact with content below the image before the reflow, the logical solution is to make your website load faster.
However, if you have users with a really slow connection, you might want to manually add the image to the markdown in HTML. See the short answer for a code example.

Related

Why would I need image placeholder service or library?

Yesterday, I saw a tweet saying about holderJS library. When I read the usage, it says it will generate the image placeholder completely on client side. So I am wondering why in the life would I need a placeholder library?
What is the scenario in which rather than placing div of some size I would use image placeholder?
Image placeholders are generally meant for a page that is either in the process of dynamically loading a real image or the page is only partially designed and the placeholder image shows how the design will be laid out and how big the image should be even though the real image is not yet available. In this way, the HTML design can be nearly completed even though the final images are not yet available or done.
Wikipedia uses image placeholders when they know they want a particular image in a page, but are in search of an image they can use with the appropriate license.
Image placeholders are traditionally served up by a service on the web that automatically creates the placeholder images based on query parameters in a URL, but the holder.js library creates placeholder images entirely on the client (so no outside services are needed).
You can certainly achieve the same look as a placeholder with just a div with a background color and perhaps even some text in the div. But, when someone wanted to plug the final images into place, they would have the change the div tags to img tags. When using a placeholder image, all the HTML tags can be final and left as they are, only the .src values need to be plugged in to finish the design. So, placeholder images allow you to have a closer to complete version of the HTML even though the images are not yet done. It's a minor different, but one that is appreciated by some designers.

Mediawiki Image Resizing - Trying to understand how it works

I have Mediawiki 1.21.2 installed. I have also set up ImageMagick on my server and have enabled it in LocalSettings.php. I have already read the Mediawiki's Images manual and I just need to clarify this:
If I am adding a plain image without adding the "thumb" option, will the image be automatically resized for the width I have mentioned or will it only skrink the dimension to that size but still has the original file size? For example, if I using this:
[[File:Sample_Image.jpg|250px]]
In the above statement, I can see that the image will be displayed with the maximum width of 250px. Lets say, if the original image is like 800px X 600px with a file size of 2MB, will the re-sized image for the above dimension will be reduced to only a few KB when the image is reduced to a width of 250px (or) will the image size shown in the article page will still have the original filesize of 2MB but only shrinked to 250px width but doesnt reduce the original filesize? I am just wondering since a lot of my users upload big pictures and these pictures have big file sizes. At the moment, I have added the image like this in my templates:
<div class="main_article_image">[[File:Sample_Image.jpg]]</div>
and then using css, I have minimized the image size like this:
.main_article_image {
max-width: 250px;
height: auto;
}
The current method resizes the images in the articles pages but the file size for these images are still huge and the article page takes too long to load. So I manually resize all images and upload a smaller size for images each time that takes more manual work. Therefore, I am trying to find out if adding the 250px with the image tag like: [[File:Sample_Image.jpg|250px]] will automate this work for me!
I have these settings on my LocalSettings.php for imagemagic:
$wgEnableUploads = true;
$wgGenerateThumbnailOnParse = true;
$wgUseImageMagick = true;
$wgImageMagickConvertCommand = "/usr/local/cpanel/3rdparty/bin/convert";
Can someone please confirm if this will work? Am I doing it the wrong way by resizing it via css? I know adding "thumb" parameter resizes the image, but will it work the same if for plain images without the thumb parameter? If it will, then I need to edit all of my templates and I just want to confirm before I go ahead changing the templates. Anyone who can clarify this will be helpful for me.
Yes, it seems that a smaller image file is generated even without the "thumb" parameter.
For example if you check the help page on images with the example "[[File:Example.jpg|50px]]" and check the url of the small image that is displayed, you'll see that it uses the thumb version /thumb/a/a9/Example.jpg/50px-Example.jpg instead of the full-size version /a/a9/Example.jpg

How to set size for local image using knitr for markdown?

I have a local image that I would like to include in an .Rmd file which I will then knit and convert to HTML slides with Pandoc. Per this post, this will insert the local image :
![Image Title](path/to/your/image)
Is there a way to modify this code to also set the image size?
The question is old, but still receives a lot of attention. As the existing answers are outdated, here a more up-to-date solution:
Resizing local images
As of knitr 1.12, there is the function include_graphics. From ?include_graphics (emphasis mine):
The major advantage of using this function is that it is portable in the sense that it works for all document formats that knitr supports, so you do not need to think if you have to use, for example, LaTeX or Markdown syntax, to embed an external image. Chunk options related to graphics output that work for normal R plots also work for these images, such as out.width and out.height.
Example:
```{r, out.width = "400px"}
knitr::include_graphics("path/to/image.png")
```
Advantages:
Over agastudy's answer: No need for external libraries or for re-rastering the image.
Over Shruti Kapoor's answer: No need to manually write HTML. Besides, the image is included in the self-contained version of the file.
Including generated images
To compose the path to a plot that is generated in a chunk (but not included), the chunk options opts_current$get("fig.path") (path to figure directory) as well as opts_current$get("label") (label of current chunk) may be useful. The following example uses fig.path to include the second of two images which were generated (but not displayed) in the first chunk:
```{r generate_figures, fig.show = "hide"}
library(knitr)
plot(1:10, col = "green")
plot(1:10, col = "red")
```
```{r}
include_graphics(sprintf("%sgenerate_figures-2.png", opts_current$get("fig.path")))
```
The general pattern of figure paths is [fig.path]/[chunklabel]-[i].[ext], where chunklabel is the label of the chunk where the plot has been generated, i is the plot index (within this chunk) and ext is the file extension (by default png in RMarkdown documents).
Un updated answer: in knitr 1.17 you can simply use
![Image Title](path/to/your/image){width=250px}
edit as per comment from #jsb
Note this works only without spaces, e.g. {width=250px} not {width = 250px}
You can also read the image using png package for example and plot it like a regular plot using grid.raster from the grid package.
```{r fig.width=1, fig.height=10,echo=FALSE}
library(png)
library(grid)
img <- readPNG("path/to/your/image")
grid.raster(img)
```
With this method you have full control of the size of you image.
Here's some options that keep the file self-contained without retastering the image:
Wrap the image in div tags
<div style="width:300px; height:200px">
![Image](path/to/image)
</div>
Use a stylesheet
test.Rmd
---
title: test
output: html_document
css: test.css
---
## Page with an image {#myImagePage}
![Image](path/to/image)
test.css
#myImagePage img {
width: 400px;
height: 200px;
}
If you have more than one image you might need to use the nth-child pseudo-selector for this second option.
If you are converting to HTML, you can set the size of the image using HTML syntax using:
<img src="path/to/image" height="400px" width="300px" />
or whatever height and width you would want to give.
Had the same issue today and found another option with knitr 1.16 when knitting to PDF (which requires that you have pandoc installed):
![Image Title](path/to/your/image){width=70%}
This method may require that you do a bit of trial and error to find the size that works for you. It is especially convenient because it makes putting two images side by side a prettier process. For example:
![Image 1](path/to/image1){width=70%}![Image 2](path/to/image2){width=30%}
You can get creative and stack a couple of these side by side and size them as you see fit. See https://rpubs.com/RatherBit/90926 for more ideas and examples.
Another option that worked for me is playing with the dpi option of knitr::include_graphics() like this:
```{r}
knitr::include_graphics("path/to/image.png", dpi = 100)
```
... which sure (unless you do the math) is trial and error compared to defining dimensions in the chunk, but maybe it will help somebody.
The knitr::include_graphics solution worked well for resizing the figures, but I was unable to figure out how to use it to produce side-by-side resized figures. I found this post useful for doing so.

Why does the add_image_size() function not create a copy of the thumbnail image in wordpress?

I have uploaded a photo in WordPress. I am trying to post a thumbnail of the image using a predetermined width while constraining the height proportionally.
In functions.js:
add_image_size('width-130', 130, 0, false);
On the page that outputs the thumbnail:
the_post_thumbnail('width-130');
According to the WordPress docs(http://codex.wordpress.org/Function_Reference/add_image_size), it says:
WordPress will create a copy of the post thumbnail with the specified
dimensions when you upload a new thumbnail.
Currently it is outputting the full thumbnail image with a width attribute of 130. This still requires the full size image to load, which is not what I want. I would like for WordPress to create an actual copy of the post thumbnail with the correct dimensions, and not just to set the width attribute. How can I achieve this?
I discovered my mistake.
Since I had not re-uploaded the image file, it was still trying to access the full size image which was the assigned image for that post, while adding the width attribute. Once I re-uploaded the image, the add_image_size() function is now actually creating a copy of the thumbnail with the correct dimensions.
I apologize for asking this question. If the community wants, I can close it but I figure it might be good reference for WordPress newbies such as myself.
Use this plugin to regenerate thumbnails.
http://wordpress.org/plugins/regenerate-thumbnails/
In case anyone runs across a similar problem, this may help. add_image_size generates derivatives that are smaller, but not bigger or the same size. Thus if you are trying to make a monochrome derivative image, uploading an image the same size as the monochrome, it will not be available and techniques like this one won't work.

Is it possible set the JPEG quality using the get_serving_url() in Google App Engine?

When using get_serving_url(user.photoBlobKey) to return an image URL from the GAE Blobstore, the Google Images API returns a JPEG image with quality = 70 and size = 512px as default.
Is there any way to increase the default JPEG quality returned by get_serving_url()?
There's an undocumented URL parameter l, you can add it to the end of the image URL like so: =l100 (or =s640-l70 if you have another param before it) that should modify the output quality of the JPEG. Seems to be =l1 to =l100.
See also: List of all the App Engine images service get_serving_url() URI options
No there is not.
If you think it's a useful feature you can add an item to the issue tracker, from there the team will assess the demand for implementing it.
you can't control the output quality but by requesting
get_serving_url(user.photoBlobKey, size=0)
you will get the original size of the image up to 1600px height and width.
the returned url will be automatically postfixed with =s0 which you could add also before rendering the image in the template for example.

Resources