Package: imgix
imgix-pythonis a client library for generating image URLs withimgix.InstallationUsageSigned URLsDisabled Path EncodingSrcset GenerationFixed-Width ImagesVariable QualityFluid-Width ImagesCustom WidthsWidth RangesWidth ToleranceExplore Target WidthsUsage with UTF-8TheixlibParameterTestingLicenseInstallationpipinstallimgixUsageTo begin creating imgix URLs, import the imgix library and create a URL builder. The URL builder can be reused to create URLs for any images on the domains it is provided.>>>fromimgiximportUrlBuilder>>>ub=UrlBuilder("demo.imgix.net")>>>ub.create_url("bridge.png",{'w':100,'h':100})'https://demo.imgix.net/bridge.png?h=100&w=100'HTTPSsupport is enabled by default.HTTPcan be toggled on by settinguse_httpstoFalse:>>>fromimgiximportUrlBuilder>>>ub=UrlBuilder("demo.imgix.net",use_https=False)>>>ub.create_url("/bridge.png",{'w':100,'h':100})'http://demo.imgix.net/bridge.png?h=100&w=100'Signed URLsTo produce a signed URL, you must enable secure URLs on your source and then provide your signature key to the URL builder.>>>fromimgiximportUrlBuilder>>>ub=UrlBuilder("demo.imgix.net",sign_key="test1234")>>>ub.create_url("/bridge.png",{'w':100,'h':100})'https://demo.imgix.net/bridge.png?h=100&w=100&s=bb8f3a2ab832e35997456823272103a4'Disabled Path EncodingPath encoding is enabled by default. It can be toggled off by settingdisable_path_encodingtoTruein the optionaloptionsparamater increate_url()andcreate_srcset()functions:>>>fromimgiximportUrlBuilder>>>ub=UrlBuilder("sdk-test.imgix.net")>>>ub.create_url(" <>[]{}|^%.jpg",params={'w':100,'h':100},options={'disable_path_encoding':True})'https://sdk-test.imgix.net/ <>[]{}|^%.jpg?h=100&w=100'Normally this would output a source URL likehttps://demo.imgix.net/%20%3C%3E%5B%5D%7B%7D%7C%5E%25.jpg?h=100&2=100, but since path encoding is disabled, it will output a source URL likehttps://sdk-test.imgix.net/ <>[]{}|^%.jpg?h=100&w=100.>>>fromimgiximportUrlBuilder>>>ub=UrlBuilder("sdk-test.imgix.net")>>>ub.create_srcset("image<>[]{}123.png",widths=[100],options={'disable_path_encoding':True})'https://sdk-test.imgix.net/image<>[]{}123.png?w=100 100w'Normally this would output a source URL likehttps://sdk-test.imgix.net/image%3C%3E%5B%5D%7B%7D%20123.png?&w=100 100w, but since path encoding is disabled, it will output a source URL likehttps://sdk-test.imgix.net//image<>[]{} 123.png?w=100 100w.Srcset GenerationThe imgix-python package allows for generation of custom srcset attributes, which can be invoked through thecreate_srcsetmethod. By default, the generated srcset will allow for responsive size switching by building a list of image-width mappings.importosfromimgiximportUrlBuilder# Keep Your Secrets Safe!SECRET=os.getenv("IX_SIGN_KEY")ub=UrlBuilder("demos.imgix.net",sign_key=SECRET)srcset=ub.create_srcset("image.png")The above will produce the following srcset attribute value which can then be served to the client:https://demos.imgix.net/image.png?w=100&s=e415797545a77a9d2842dedcfe539c9a 100w,
https://demos.imgix.net/image.png?w=116&s=b2da46f5c23ef13d5da30f0a4545f33f 116w,
https://demos.imgix.net/image.png?w=135&s=b61422dead929f893c04b8ff839bb088 135w,
                                        ...
https://demos.imgix.net/image.png?w=7401&s=ad671301ed4663c3ce6e84cb646acb96 7401w,
https://demos.imgix.net/image.png?w=8192&s=a0fed46e2bbcc70ded13dc629aee5398 8192wFixed-Width ImagesIn cases where enough information is provided about an image's dimensions,create_srcsetwill instead build a srcset that will allow for an image to be served at different resolutions. The parameters taken into consideration when determining if an image is fixed-width arew,h, andar.By invokingcreate_srcsetwith either a widthorthe height and aspect ratio (along withfit=crop, typically) provided, a different srcset will be generated for a fixed-width image instead.fromimgiximportUrlBuilder>>>ub=UrlBuilder("demos.imgix.net",sign_key="my-token")>>>srcset=ub.create_srcset("image.png",{'h':800,'ar':'3:2','fit':'crop'})Will produce the following attribute value:https://demos.imgix.net/image.png?ar=3%3A2&dpr=1&fit=crop&h=800&s=6cf5c443d1eb98bc3d96ea569fcef088 1x,
https://demos.imgix.net/image.png?ar=3%3A2&dpr=2&fit=crop&h=800&s=d60a61a5f34545922bd8dff4e53a0555 2x,
https://demos.imgix.net/image.png?ar=3%3A2&dpr=3&fit=crop&h=800&s=590f96aa426f8589eb7e449ebbeb66e7 3x,
https://demos.imgix.net/image.png?ar=3%3A2&dpr=4&fit=crop&h=800&s=c89c2fd3148957647e86cfc32ba20517 4x,
https://demos.imgix.net/image.png?ar=3%3A2&dpr=5&fit=crop&h=800&s=3d73af69d78d49eef0f81b4b5d718a2c 5xBy default, this library generates asrcsetwith pixel density values of1through5.
These target ratios can be controlled by using thedevicePixelRatiosparameters.fromimgiximportUrlBuilderclient=UrlBuilder("demo.imgix.net")client.create_srcset("image.jpg",{"w":100},{"device_pixel_ratios":[1,2,3]})Will produce the following attribute value:https://demo.imgix.net/image.jpg?dpr=1&ixlib=python-3.2.1&q=75&w=100 1x,
https://demo.imgix.net/image.jpg?dpr=2&ixlib=python-3.2.1&q=50&w=100 2x,
https://demo.imgix.net/image.jpg?dpr=3&ixlib=python-3.2.1&q=35&w=100 3x'For more information to better understand srcset, we highly recommendEric Portis' "Srcset and sizes" articlewhich goes into depth about the subject.Variable QualityThis library will automatically append a variableqparameter mapped to eachdprparameter when generating afixed-width imagesrcset. This technique is commonly used to compensate for the increased file size of high-DPR images.Since high-DPR images are displayed at a higher pixel density on devices, image quality can be lowered to reduce overall file size––without sacrificing perceived visual quality. For more information and examples of this technique in action, seethis blog post.This behavior will respect any overridingqvalue passed in as a parameter. Additionally, it can be disabled altogether by passingdisable_variable_quality = truetocreate_srcset.This behavior specifically occurs when afixed-width imageis rendered, for example:# Note that `params={"w": 100}` allows `create_srcset` to _infer_ the creation# of a DPR based srcset attribute for fixed-width images.ub=imgix.UrlBuilder('demo.imgix.net')# Set `disable_variable_quality` to True to disable variable quality.srcset=ub.create_srcset('image.jpg',params={"w":100},disable_variable_quality=False)The above will generate a srcset with the followingqtodprqueryparams:https://demo.imgix.net/image.jpg?w=100&dpr=1&q=75 1x,
https://demo.imgix.net/image.jpg?w=100&dpr=2&q=50 2x,
https://demo.imgix.net/image.jpg?w=100&dpr=3&q=35 3x,
https://demo.imgix.net/image.jpg?w=100&dpr=4&q=23 4x,
https://demo.imgix.net/image.jpg?w=100&dpr=5&q=20 5xBy default, this library will automatically append a variableqparameter mapped to eachdprparameter when generating afixed-width imagesrcset.To customize variable qualities, you can pass avariable_qualitiesdictionary in theoptionswhile creating srcset as below:fromimgiximportUrlBuilderclient=UrlBuilder("demo.imgix.net")client.create_srcset("image.jpg",{"w":100},{"variable_qualities":{1:45,2:30,3:20,4:15,5:10}})The above script will produce the following output:https://demo.imgix.net/image.jpg?dpr=1&q=45&w=1001x
https://demo.imgix.net/image.jpg?dpr=2&q=30&w=1002x
https://demo.imgix.net/image.jpg?dpr=3&q=20&w=1003x
https://demo.imgix.net/image.jpg?dpr=4&&q=15&w=1004x
https://demo.imgix.net/image.jpg?dpr=5&q=10&w=1005xYou can also passvariable_qualitiesalong with thedevice_pixel_ratiosoption as below:fromimgiximportUrlBuilderclient=UrlBuilder("demo.imgix.net")client.create_srcset("image.jpg",{"w":100},{"device_pixel_ratios":[1,2,3],"variable_qualities":{1:45,2:30,3:20}})The above script will produce the following output:https://testing.imgix.net/image.jpg?dpr=1&q=45&w=100 1x,
https://testing.imgix.net/image.jpg?dpr=2&q=30&w=100 2x,
https://testing.imgix.net/image.jpg?dpr=3&q=20&w=100 3xFluid-Width ImagesCustom WidthsIn situations where specific widths are desired when generatingsrcsetpairs, a user can specify them by passing an array of positive integers aswidths:>>>fromimgiximportUrlBuilder>>>builder=UrlBuilder('demo.imgix.net')>>>builder.create_srcset('image.jpg',widths=[144,240,320,446,640])'https://demo.imgix.net/image.jpg?w=144 144w,\nhttps://demo.imgix.net/image.jpg?w=240 240w,\nhttps://demo.imgix.net/image.jpg?w=320 320w,\nhttps://demo.imgix.net/image.jpg?w=446 446w,\nhttps://demo.imgix.net/image.jpg?w=640 640w'https://demo.imgix.net/image.jpg?w=144 144w,
https://demo.imgix.net/image.jpg?w=240 240w,
https://demo.imgix.net/image.jpg?w=320 320w,
https://demo.imgix.net/image.jpg?w=446 446w,
https://demo.imgix.net/image.jpg?w=640 640wNote: in situations where asrcsetis being rendered as afixed-widthsrcset, any customwidthspassed in will be ignored.Additionally, if bothwidthsand a widthtolerance are passed to thecreate_srcsetmethod, the custom widths list will take precedence.Width RangesIn certain circumstances, you may want to limit the minimum or maximum value of the non-fixedsrcsetgenerated by thecreate_srcsetmethod. To do this, you can specify the widths at which a srcset shouldstartandstop:>>>fromimgiximportUrlBuilder>>>ub=UrlBuilder('demo.imgix.net')>>>ub.create_srcset('image.jpg',start=500,stop=2000)'https://demo.imgix.net/image.jpg?w=500 500w,\nhttps://demo.imgix.net/image.jpg?w=580 580w,\nhttps://demo.imgix.net/image.jpg?w=673 673w,\nhttps://demo.imgix.net/image.jpg?w=780 780w,\nhttps://demo.imgix.net/image.jpg?w=905 905w,\nhttps://demo.imgix.net/image.jpg?w=1050 1050w,\nhttps://demo.imgix.net/image.jpg?w=1218 1218w,\nhttps://demo.imgix.net/image.jpg?w=1413 1413w,\nhttps://demo.imgix.net/image.jpg?w=1639 1639w,\nhttps://demo.imgix.net/image.jpg?w=1901 1901w,\nhttps://demo.imgix.net/image.jpg?w=2000 2000w'Formatted version of the above srcset attribute:https://demo.imgix.net/image.jpg?w=500 500w,
https://demo.imgix.net/image.jpg?w=580 580w,
https://demo.imgix.net/image.jpg?w=673 673w,
https://demo.imgix.net/image.jpg?w=780 780w,
https://demo.imgix.net/image.jpg?w=905 905w,
https://demo.imgix.net/image.jpg?w=1050 1050w,
https://demo.imgix.net/image.jpg?w=1218 1218w,
https://demo.imgix.net/image.jpg?w=1413 1413w,
https://demo.imgix.net/image.jpg?w=1639 1639w,
https://demo.imgix.net/image.jpg?w=1901 1901w,
https://demo.imgix.net/image.jpg?w=2000 2000w'Width ToleranceThesrcsetwidthtolerance dictates the maximumtolerated difference between an image's downloaded size and its rendered size.For example, setting this value to0.10means that an image will not render more than 10% larger or smaller than its native size. In practice, the image URLs generated for a width-based srcset attribute will grow by twice this rate.A lower tolerance means images will render closer to their native size (thereby increasing perceived image quality), but a large srcset list will be generated and consequently users may experience lower rates of cache-hit for pre-rendered images on your site.By default, srcset widthtolerance is set to 0.08 (8 percent), which we consider to be the ideal rate for maximizing cache hits without sacrificing visual quality. Users can specify their own width tolerance by providing a positive scalar value as widthtolerance:>>>importimgix>>>ub=imgix.UrlBuilder('demo.imgix.net')>>>srcset=ub.create_srcset('image.jpg',start=100,stop=384,tol=0.20)In this case, thewidth_toleranceis set to 20 percent, which will be reflected in the difference between subsequent widths in a srcset pair:https://demo.imgix.net/image.jpg?w=100 100w,
https://demo.imgix.net/image.jpg?w=140 140w,
https://demo.imgix.net/image.jpg?w=196 196w,
https://demo.imgix.net/image.jpg?w=274 274w,
https://demo.imgix.net/image.jpg?w=384 384wExplore Target WidthsThetarget_widthsfunction is used internally to generate lists of target widths to be used in calls tocreate_srcset.It is a way to generate, play with, and explore different target widths separately from srcset attributes. One way of generating a srcset attribute is:srcset=ub.create_srcset('image.jpg',start=300,stop=3000,tol=0.13)The above is convenient ifstart,stop, andtolerance are known in advance. Another approach is to usetarget_widthsto determine which combination of values forstart,stop, andtolerance work best.>>>fromimgiximportUrlBuilder,target_widths>>># Create>>>widths=target_widths(300,3000,0.13)>>>widths[300,378,476,600,756,953,1200,1513,1906,2401,3000]>>># Explore>>>sm,md,lg=widths[:3],widths[3:7],widths[7:]>>>widths=[wforwinwidths[1::2]]>>>widths[378,600,953,1513,2401]>>># Serve>>>ub=UrlBuilder('demo.imgix.net')>>>srcset=ub.create_srcset('image.png',widths=widths)>>>srcset'https://demo.imgix.net/image.png?w=378 378w,\nhttps://demo.imgix.net/image.png?w=600 600w,\nhttps://demo.imgix.net/image.png?w=953 953w,\nhttps://demo.imgix.net/image.png?w=1513 1513w,\nhttps://demo.imgix.net/image.png?w=2401 2401w'Usage with UTF-8For usage with non-ASCII characters, please be sure that your project's source files specify UTF-8 encoding:# -*- coding: utf-8 -*-If you don't add this encoding, and you have an image with the name 'tiburón.jpeg', for example, you will get the following error trying to run your script:SyntaxError:Non-ASCIIcharacter'***'infiletest.pyonline6,butnoencodingdeclared;seehttp://www.python.org/peps/pep-0263.htmlfordetailsTheixlibParameterFor security and diagnostic purposes, we sign all requests with the language and version of library used to generate the URL.This can be disabled by settinginclude_library_paramtoFalselike so:UrlBuilder('demo.imgix.net',include_library_param=False)TestingRun the following to execute the project's tests and code linter:toxIf you have cloned this repo or downloaded it locally, you can also runpython -m doctest -v README.mdto test the examples in this readme.LicenseChangelog4.0.0(2022-12-08)Breaking Changesfeat: drop python 2 support (#88)fix: fixed-height produces dpr-based srcset (#88)feat: encode file path components (#88)Featuresfeat: add path encoding to be disabled optionally (#98)feat: customize variable qualities in options (#102)feat: customize target device pixel ratios (#103)3.2.1(2020-06-10)refactor: relax validation for min/max width values (#80)3.2.0(2020-06-05)feat: create custom srcset (#63)feat: introduce variable image output quality (#65)fix: remove ensure even (#72)feat: throw exceptions from validators (#77)fix: convert tol to float (#75)3.1.2(2020-03-11)Fix Python 2/3 compatibility issues
(#57)3.1.1(2019-08-22)fix: include dpr parameter when generating fixed-width srcset
(#50)3.1.0(2019-08-22)feat: add srcset generation
(#48)build(tox): improve code coverage reporting; parallelize testing
(#49)3.0.0(2019-06-07)fix: remove deprecated domain sharding functionality
(#44)fix: remove deprecated [opts]{.title-ref} parameter
(#46)fix: remove deprecated [sign_with_library_version]{.title-ref}
parameter (#47)2.3.0(2019-06-06)feat: deprecate [domains]{.title-ref} in favor of
[domain]{.title-ref}
(#45)2.2.0(2019-05-07)deprecate domain sharding
(#41)(#42)2.1.0 (2019-02-13)Domain validation added during [UrlBuilder]{.title-ref}
initialization[sign_with_library_version]{.title-ref} parameter from
[UrlBuilder]{.title-ref} deprecated in favor of
[include_library_param]{.title-ref}.2.0.0 (2018-08-08)[UrlBuilder]{.title-ref}'s [sign_mode]{.title-ref} argument
removed[opts]{.title-ref} parameter from
[UrlBuilder.create_url]{.title-ref} deprecated in favor of
[params]{.title-ref}.1.2.0 (2018-06-20)[sign_mode]{.title-ref} argument deprecatedLicense corrected to BSD-2-Clause.Docstrings added to classes and methods.1.1.2 (2016-06-30)Proper encodeURIComponent-style URL encoding for web proxy sources.
See #21 for more information.1.1.0 (2016-02-26)Added automatic Base64 encoding for all Base64 variant parameters.Properly encoding all query keys and values.1.0.0 (2016-01-15)Change UrlBuilder#create_url to accept dict instead of kwargs.
This fixes an issue with reserved words that are also imgix params
potentially causing errors.0.2.1 (2016-01-15)Fixed a bug where any passed params that were falsy would not be
passed through to imgix.0.2.0 (2015-06-15)Introduces defaulting to HTTPS on all requests, per the
imgix-blueprint.0.1.0 (2015-06-11)Includes new functionality to sign every URL with an ixlib parameter
for diagnostic purposes.0.0.4 (2015-06-10)New README note about publishing packages