The image topic is for questions related to the loading, formatting, saving, compression, and display of images in the context of source code.
Bongani  Ngema

Bongani Ngema


How to Programatically Change HTML Image Src Attribute Use JavaScript

Change HTML image src using JavaScript code

You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.

After you have the element, you can assign a new string value to its src property as follows:

  <img id="banner" src="image.jpg" />
    const img = document.getElementById("banner");
    img.src = "newImage.png";

When you have the image in another folder, than you need to add the image path to the src attribute as well. The code below shows how to change the src attribute to an image inside the assets/ folder:

img.src = "./assets/newImage.png";

Finally, if you need to run some JavaScript code after a new image has been loaded to the element, you can add an onload event loader to your img element before changing the src attribute as follows:

const img = document.getElementById("banner");
img.onload = function () {
  alert("New image has been loaded");
img.src = "newImage.png";

Using the above code, an alert will be triggered when the new image from the src attribute has been loaded to the HTML page.

Original article source at:

#javascript #html #image 

How to Programatically Change HTML Image Src Attribute Use JavaScript
Monty  Boehm

Monty Boehm


How to Changing Webpage Background Image using JavaScript Code

JavaScript: change a webpage background image tutorial

When you want to change a webpage background image using JavaScript, you can do so by setting the background image of the document object model (DOM) property.

The property you need to manipulate for changing the background image of the whole page is = "url('image.png')";

You need to put the relative path to the image from your web page’s folder. If the image is located in the same folder, then you can reference it directly inside the url() function as in the code above.

When the image is one folder down, add the correct relative path as follows: = "url('./assets/image.png')";

Or go up one folder with the following relative path: = "url('../image.png')";

If you have the image URL available publicly on the internet, you can pass the full url into the property as in the following example: =

The code above will change the background image into an image that I have created for my website. You can test the code out by changing the image of Google’s homepage. First, open your browser’s developer console. Then in the Console tab next to Elements tab, write the following code: =

The background image of Google’s homepage will change to the specified image, just like in the screenshot below:

Changing the background image of Google

Changing the background image of Google

By default, the image you selected as a background will be repeated to cover the whole page. You may want to style the background image further by setting the background-repeat style to "no-repeat" and the background-size style to "cover".

To add the extra styles using JavaScript, you need to set the style property, which contains the same styling property but with a camelCase instead of kebab-case. For example, background-repeat becomes backgroundRepeat: = "no-repeat"; = "cover";

Inside your web application, you may want to trigger the background image change when the visitors do something. For example, you can change the background image when a <button> is clicked:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>JavaScript change background image</title>
      // The function below will change the background image
      function changeBackgroundImage() { = "url('image.png')"; = "no-repeat"; = "cover";
    <h1>Click the button to change the background image:</h1>
    <button onclick="changeBackgroundImage();">Change</button>

Or you can also immediately change the background image after the page is loaded by listening to the DOMContentLoaded event as follows:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>JavaScript change background image</title>
      // The function below will change the background image
      function changeBackgroundImage() { = "url('image.png')";
      // call the function when the whole DOM content is loaded
      document.addEventListener("DOMContentLoaded", changeBackgroundImage());
    <h1>Change the background image on load</h1>

The DOMContentLoaded event is triggered when your whole HTML page has been loaded, even though some external JavaScript, CSS, and image resources are not yet fully loaded.

If you want to wait until the page and the resources are fully loaded, you can listen for the load event instead:

document.addEventListener("load", changeBackgroundImage());

Changing the background image of a specific element

The document.body code means you are selecting the <body> tag of your HTML page. You can also change only a part of your page by selecting only that specific element.

The browser provides you with several ways to select a specific element:

  • getElementById() - get a single element with matching id attribute
  • getElementsByClassName() - get elements with matching class attribute
  • getElementsByName() - get elements with matching name attribute
  • getElementsByTagName() - get elements with matching tag name like "li" for <li>, "body" for <body>

The most recommended approach is to use getElementById() because it’s the most specific of these methods. Out of the four methods, only getElementById() will retrieve a single element.

The following example shows how you can change the background of <div> element with id="user" attribute:

<!DOCTYPE html>
<html lang="en">
    <meta charset="utf-8" />
    <title>JavaScript change background image</title>
      // change the background image of div user
      function changeBackgroundUser() {
        document.getElementById("user").style.backgroundImage =
    <div id="user">
      <h1>Change specific DIV background image</h1>
    <div id="guest">
      <h2>This element's parent DIV background won't be changed</h2>
    <div id="stranger">
      <h2>Neither this one</h2>
    <button onclick="changeBackgroundUser();">Change BG image</button>

Finally, you can put the bgImage as a parameter to the changeBackgroundImage() function so that you can have buttons that change the background to different images:

  // change the background image using the passed parameter
  function changeBackgroundImage(bgImage) { = "url(" + bgImage + ")";

<button onclick="changeBackgroundImage('image.png');">Use image.png</button>
<button onclick="changeBackgroundImage('pic.jpg');">Use pic.jpg</button>
<button onclick="changeBackgroundImage('user.png');">Use user.png</button>

And that’s how you change the background image of a webpage using JavaScript 😉

Original article source at:

#javascript #webpage #image 

How to Changing Webpage Background Image using JavaScript Code
Sheldon  Grant

Sheldon Grant


How to Save JavaScript Canvas Image As Data URL using ToDataURL()

Saving canvas image as Data URL using toDataURL() method

The toDataURL() method is a method from the Canvas API that allows you to store an image drawn on top of the <canvas> element in the form of a Data URL scheme.

The Data URL scheme allows you to embed an image in-line inside your HTML, saving you one extra HTTP request that would otherwise be performed for that image.

The method accepts two optional parameters:

  • The type string for the image format. Defaults to image/png
  • The imageQuality number for image types that use lossy compression like image/jpeg. The value must be between 0 and 1 with the default value being 0.92

Let’s see the method in action. Suppose you’ve created a <canvas> element as follows:

    let canvas = document.getElementById("emptyCanvas");
    let ctx = canvas.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.fillRect(50, 100, 150, 150);

The code above will produce a rectangle drawing in your web browser as follows:

An image created using HTML CanvasAn image created using HTML Canvas

To transform the image drawn into a Data URL, you only need to call the toDataURI() method on the canvas object:

const dataURL = canvas.toDataURL();

The console.log() result would be as follows. The ellipsis ... in the second line omits the rest of the output and the third line shows the end of the URI:


The format of the scheme is as shown below:

data:[<mime type>][;charset=<charset>][;base64],<encoded data>

The encoded data is a very long string that the browser will render as an image. You need to pass the entire scheme as the src attribute of an <img> element.

To test the data scheme, you can copy and pass the Data URL into a new browser window to see the image rendered using the <img> element. Notice how the data:image/png scheme entered into the address bar below:

Image Data URL rendered on the browserImage Data URL rendered on the browser

By transforming the image to a Data URL scheme, you can embed any image rendered inside the <canvas> element in any web page without making an extra HTTP request.

But keep in mind that the Data URL scheme is not recommended for large images or images that are changed frequently because the scheme is not cached by the browser, meaning that the image will be downloaded each time the page is loaded.

On the other hand, an HTTP request for the image can be cached by the browser so that the image will be served from the cache when the page is loaded again.

Original article source at:

#javascript #image #canvas 

How to Save JavaScript Canvas Image As Data URL using ToDataURL()

How to create HTML image elements using JavaScript

Learn how you can create an image element and add it to your HTML document using JavaScript

There are two ways you can create an HTML image element using JavaScript:

  • Using the document.createElement('img') syntax
  • Using the Image() constructor

Let’s learn how to use these two methods to create an HTML image element.

Create image using JavaScript createElement API

The document.createElement() method is a method of the document object that allows you to create an instance of HTML elements.

You need to pass the HTML element tag name as an argument to the createElement() method to create one:

let paragraph = document.createElement("p");

let image = document.createElement("img");

Once you’ve created the element, you can modify its properties like any other HTML element.

After that, you need to append the image to the HTML <body> tag to make it visible:

let image = document.createElement("img");
image.src = "image.png";
image.width = 300;
image.height = 200;


By appending the image using the document.body.appendChild() method, you will have the following HTML document structure:

  <img src="image.png" width="300" height="200" />

And that’s how you create an HTML element using the document.createElement() method.

Create image using JavaScript Image() constructor

The JavaScript Image() constructor is used to create an HTML image element, similar to how the document.createElement('img') syntax works.

To create an image using the constructor, you need to call the constructor as follows:

let image = new Image();

The constructor accepts two optional arguments:

  • width for the image’s width attribute
  • height for the image’s height attribute

Here’s an example of creating an image using the Image() constructor:

let image = new Image(300, 200);
image.src = "image.png";

// <img width="300" height="200" src="image.png">

And that’s how you create an HTML image element using the Image() constructor.

Keep in mind that the document object and the Image() constructor are parts of the Web API. They are not available in other JavaScript environments like NodeJS.

Good work in learning how to create images using JavaScript. 👍

Original article source at:

#javascript #image #elements #html 

How to create HTML image elements using JavaScript

How to Output an Image To The Browser using PHP Echo

See how you output an image to the browser using PHP echo.

To get an image displayed on the browser using PHP, you can echo an <img> tag as follows:

echo '<img src="my-picture.png" alt="My image" />';

You need to replace my-picture.png with your actual picture name.

If the picture is not located in the same path as the PHP file, you need to write the right path.

Keep in mind that you need to use a different quote symbol then the one you use in the echo statement.

If you use single quotes for the echo statement, then use double quotes to avoid unexpected identifier error.

See the example below:

echo '<img src="my-picture.png" alt="My image" />';
// or
echo "<img src='my-picture.png' alt='My image' />";

You need to choose one of the two styles above and make it consistent on all your PHP files.

And that’s how you echo an image using PHP 😉

Original article source at:

#php #image #browser 

How to Output an Image To The Browser using PHP Echo

How to Adding Background Image using jQuery

A guide on adding background image using jQuery

With jQuery, you can change the background-image CSS property by using the css() method. The method is used to set or retrieve one CSS property value.

The syntax of css() method is as follows:

css("propertyName", "value");

You can set the background-image property, to any element you’ve selected using jQuery selector method:

$('.imgEl').css('background-image', 'url(./assets/image.png)');

Finally, you can also set other CSS properties to make the background looks good on your page, such as background-repeat, background-position, and height properties as follows:

$('.imgEl').css('background-image', 'url(./assets/image.png)');
$('.imgEl').css('background-repeat', 'no-repeat'); // do not repeat the image
$('.imgEl').css('background-position', 'center'); // center the image
$('.imgEl').css('height', '500px'); // sets the height

And that’s how you can change background image using jQuery 😉

Original article source at:

#jquery #background #image 

How to Adding Background Image using jQuery
Nat  Grady

Nat Grady


Magick: Magic, Madness, Heaven, Sin

rOpenSci: The magick package 

Advanced Image-Processing in R

Bindings to ImageMagick: the most comprehensive open-source image processing library available. Supports many common formats (png, jpeg, tiff, pdf, etc) and manipulations (rotate, scale, crop, trim, flip, blur, etc). All operations are vectorized via the Magick++ STL meaning they operate either on a single frame or a series of frames for working with layers, collages, or animation. In RStudio images are automatically previewed when printed to the console, resulting in an interactive editing environment.


About the R package:

About the underlying library:

Hello World

Run examples in RStudio to see live previews of the images! If you do not use RStudio, use image_browse to open images. On Linux you can also use image_display to get an X11 preview.

frink <- image_read("")
image_scale(frink, "200x200")
image_rotate(frink, 45) ## <-- result of this is shown
frink %>% 
  image_background("green") %>% 
  image_flatten() %>%
  image_border("red", "10x10")
image_rotate(frink, 45) %>% image_write("man/figures/frink-rotated.png")


image_charcoal(frink) ## <-- result of this is shown
image_charcoal(frink) %>% image_write("man/figures/frink-charcoal.png")

Create GIF animation:

# Download images
oldlogo <- image_read("")
newlogo <- image_read("")
logos <- c(oldlogo, newlogo)
logos <- image_scale(logos, "400x400")

# Create GIF
(animation1 <- image_animate(logos))
image_write(animation1, "man/figures/anim1.gif")

# Morph effect  <-- result of this is shown
(animation2 <- image_animate(image_morph(logos, frames = 10)))
image_write(animation2, "man/figures/anim2.gif")

Read GIF animation frames. See the rotating earth example GIF.

earth <- image_read("")
earth1 <- rev(image_flip(earth)) ## How Austrialans see earth
image_write(earth1, "man/figures/earth1.gif") ## <-- result of this is shown

R logo with dancing banana

logo <- image_read("")
banana <- image_read("")
front <- image_scale(banana, "300")
background <- image_scale(logo, "400")
frames <- lapply(as.list(front), function(x) image_flatten(c(background, x)))
image_write(image_animate(image_join(frames)), "man/figures/Rlogo-banana.gif")

Use magick in Shiny Apps

This demo application shows how to use magick with shiny:


Binary packages for macOS or Windows can be installed directly from CRAN:


Installation from source on Linux or OSX requires the imagemagick Magick++ library. On Debian or Ubuntu install libmagick++-dev:

sudo apt-get install -y libmagick++-dev

If you are on Ubuntu 14.04 (trusty) or 16.04 (xenial) you can get a more recent backport from the ppa:

sudo add-apt-repository -y ppa:cran/imagemagick
sudo apt-get update
sudo apt-get install -y libmagick++-dev 

On Fedora, CentOS or RHEL we need ImageMagick-c++-devel. However on CentOS the system version of ImageMagick is quite old. More recent versions are available from the ImageMagick downloads website.

sudo yum install ImageMagick-c++-devel

On macOS use imagemagick@6 from Homebrew.

brew install imagemagick@6

The unversioned homebrew formulaimagemagick can also be used, however it has some unsolved OpenMP problems.

There is also a fork of imagemagick called graphicsmagick, but this doesn't work for this package.

Download Details:

Author: ropensci
Source Code: 
License: View license

#r #image #processing #rstats 

Magick: Magic, Madness, Heaven, Sin
Royce  Reinger

Royce Reinger


Caire: Content Aware Image Resize Library


Caire is a content aware image resize library based on Seam Carving for Content-Aware Image Resizing paper.

How does it work

  • An energy map (edge detection) is generated from the provided image.
  • The algorithm tries to find the least important parts of the image taking into account the lowest energy values.
  • Using a dynamic programming approach the algorithm will generate individual seams across the image from top to down, or from left to right (depending on the horizontal or vertical resizing) and will allocate for each seam a custom value, the least important pixels having the lowest energy cost and the most important ones having the highest cost.
  • We traverse the image from the second row to the last row and compute the cumulative minimum energy for all possible connected seams for each entry.
  • The minimum energy level is calculated by summing up the current pixel value with the lowest value of the neighboring pixels obtained from the previous row.
  • We traverse the image from top to bottom and compute the minimum energy level. For each pixel in a row we compute the energy of the current pixel plus the energy of one of the three possible pixels above it.
  • Find the lowest cost seam from the energy matrix starting from the last row and remove it.
  • Repeat the process.

The process illustrated:

Original imageEnergy mapSeams applied


Key features which differentiates this library from the other existing open source solutions:

  •  GUI progress indicator
  •  Customizable command line support
  •  Support for both shrinking or enlarging the image
  •  Resize image both vertically and horizontally
  •  Face detection to avoid face deformation
  •  Support for multiple output image type (jpg, jpeg, png, bmp, gif)
  •  Support for stdin and stdout pipe commands
  •  Can process whole directories recursively and concurrently
  •  Use of sobel threshold for fine tuning
  •  Use of blur filter for increased edge detection
  •  Support for squaring the image with a single command
  •  Support for proportional scaling
  •  Support for protective mask
  •  Support for removal mask
  •  GUI debug mode support


First, install Go, set your GOPATH, and make sure $GOPATH/bin is on your PATH.

$ go install 

MacOS (Brew) install

The library can also be installed via Homebrew.

$ brew install caire


$ caire -in input.jpg -out output.jpg

Supported commands:

$ caire --help

The following flags are supported:

in-Input file
out-Output file
widthn/aNew width
heightn/aNew height
previewtrueShow GUI window
percfalseReduce image by percentage
squarefalseReduce image to square dimensions
blur4Blur radius
sobel2Sobel filter threshold
debugfalseUse debugger
facefalseUse face detection
anglefloatPlane rotated faces angle
maskstringMask file path
rmaskstringRemove mask file path
colorstringSeam color (default #ff0000)
shapestringShape type used for debugging: circle,line (default circle)

Face detection

The library is capable of detecting human faces prior resizing the images by using the lightweight Pigo ( face detection library.

The image below illustrates the application capabilities for human face detection prior resizing. It's clearly visible that with face detection activated the algorithm will avoid cropping pixels inside the detected faces, retaining the face zone unaltered.

Original imageWith face detectionWithout face detection
OriginalWith Face DetectionWithout Face Detection

Sample image source

GUI progress indicator

GUI preview

A GUI preview mode is also incorporated into the library for in time process visualization. The Gio GUI library has been used because of its robustness and modern architecture. Prior running it please make sure that you have installed all the required dependencies noted in the installation section ( .

The preview window is activated by default but you can deactivate it any time by setting the -preview flag to false. When the images are processed concurrently from a directory the preview mode is deactivated.

Face detection to avoid face deformation

In order to detect faces prior rescaling, use the -face flag. There is no need to provide a face classification file, since it's already embedded into the generated binary file. The sample code below will resize the provided image with 20%, but checks for human faces in order tot avoid face deformations.

For face detection related settings please check the Pigo documentation.

$ caire -in input.jpg -out output.jpg -face=1 -perc=1 -width=20

Support for stdin and stdout pipe commands

You can also use stdin and stdout with -:

$ cat input/source.jpg | caire -in - -out - >out.jpg

in and out default to - so you can also use:

$ cat input/source.jpg | caire >out.jpg
$ caire -out out.jpg < input/source.jpg

You can provide also an image URL for the -in flag or even use curl or wget as a pipe command in which case there is no need to use the -in flag.

$ caire -in <image_url> -out <output-folder>
$ curl -s <image_url> | caire > out.jpg

Process multiple images from a directory concurrently

The library can also process multiple images from a directory concurrently. You have to provide only the source and the destination folder and the new width or height in this case.

$ caire -in <input_folder> -out <output-folder>

Support for multiple output image type

There is no need to define the output file type, just use the correct extension and the library will encode the image to that specific type. You can export the resized image even to a Gif file, in which case the generated file shows the resizing process interactively.

Other options

In case you wish to scale down the image by a specific percentage, it can be used the -perc boolean flag. In this case the values provided for the width and height are expressed in percentage and not pixel values. For example to reduce the image dimension by 20% both horizontally and vertically you can use the following command:

$ caire -in input/source.jpg -out ./out.jpg -perc=1 -width=20 -height=20 -debug=false

Also the library supports the -square option. When this option is used the image will be resized to a square, based on the shortest edge.

When an image is resized on both the X and Y axis, the algorithm will first try to rescale it prior resizing, but also will preserve the image aspect ratio. The seam carving algorithm is applied only to the remaining points. Ex. : given an image of dimensions 2048x1536 if we want to resize to the 1024x500, the tool first rescale the image to 1024x768 and then will remove only the remaining 268px.

Masks support:

  • -mask: The path to the protective mask. The mask should be in binary format and have the same size as the input image. White areas represent regions where no seams should be carved.
  • -rmask: The path to the removal mask. The mask should be in binary format and have the same size as the input image. White areas represent regions to be removed.
MaskMask removal

Caire integrations


Shrunk images


Enlarged images


Useful resources

Download Details:

Author: esimov
Source Code: 
License: MIT license

#machinelearning #golang #computervision #image 

Caire: Content Aware Image Resize Library
Rupert  Beatty

Rupert Beatty


An Easy to Use Image Viewer That Is inspired By Facebook


An easy to use Image Viewer that is inspired by Facebook

Screenshot-dark-modeScreenshot-light-mode Screenshot-auto-rotate


  • From iOS 10
  • Swift versions
    • Swift 4.0
    • Swift 4.2
    • Swift 5.0



Using cocoapods

pod 'ImageViewer.swift', '~> 3.0'

If you need remote image fetching:

pod 'ImageViewer.swift', '~> 3.0'
pod 'ImageViewer.swift/Fetcher', '~> 3.0'


Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

github "michaelhenry/ImageViewer.swift" ~> 3.2

How to use it

The simplest way to to use this is by using the imageView.setupImageViewer()



import ImageViewer_swift

let imageView = UIImageView()
imageView.image = UIImage(named: 'cat1')

Or you might load it from a URL

imageView.setupImageViewer(url: URL(string: "")!)

Or you might load it with an array of images [UIImage]

let images = [
    UIImage(named: "cat1"),
    UIImage(named: "cat1"),
    UIImage(named: "cat1")
imageView.setupImageViewer(images: images)

Or you might load it with an array of URL [URL]

let urls = [
    URL(string: "")!,
    URL(string: "")!,
    URL(string: "")!
imageView.setupImageViewer(urls: urls)

How to change the layout or options that are available

You can check this file ImageViewerOption.swift to see what are the available options that will fit to your needs.

public enum ImageViewerOption {
    case theme(ImageViewerTheme)
    case closeIcon(UIImage)
    case rightNavItemTitle(String, onTap: ((Int) -> Void)?)
    case rightNavItemIcon(UIImage, onTap: ((Int) -> Void)?)

You could also check the Demo Project for more information.

Easy peasy :)

Please let me know if you have any questions.

Cheers, Michael Henry Pantaleon

Twitter: @michaelhenry119

Linked in: ken119


Download Details:

Author: Michaelhenry
Source Code: 

#swift #image #ios #gallery #library 

An Easy to Use Image Viewer That Is inspired By Facebook
Rupert  Beatty

Rupert Beatty


BSImagePicker: A multiple image picker for iOS


A multiple image picker for iOS.


  • Multiple selection.
  • Fullscreen preview
  • Switching albums.
  • Supports images, live photos and videos.
  • Customizable.
alt text



To be able to request permission to the users photo library you need to add this to your Info.plist

<string>Why you want to access photo library</string>

Image picker

import BSImagePicker

let imagePicker = ImagePickerController()

presentImagePicker(imagePicker, select: { (asset) in
    // User selected an asset. Do something with it. Perhaps begin processing/upload?
}, deselect: { (asset) in
    // User deselected an asset. Cancel whatever you did when asset was selected.
}, cancel: { (assets) in
    // User canceled selection. 
}, finish: { (assets) in
    // User finished selection assets.


So you have a bunch of PHAssets now, great. But how do you use them? To get an UIImage from the asset you use a PHImageManager.

import Photos

// Request the maximum size. If you only need a smaller size make sure to request that instead.
PHImageManager.default().requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFit, options: nil) { (image, info) in
    // Do something with image

For more example you can clone this repo and look at the example app.



Add the following line to your Podfile:

pod "BSImagePicker", "~> 3.1"


Add the following line to your Cartfile:

github "mikaoj/BSImagePicker" ~> 3.1

Swift Package Manager

Add it to the dependencies value of your Package.swift.:

dependencies: [
.package(url: "", from: "version-tag")


If you are Xamarin developer you can use Net.Xamarin.iOS.BSImagePicker


Users are encouraged to become active participants in its continued development — by fixing any bugs that they encounter, or by improving the documentation wherever it’s found to be lacking.

If you wish to make a change, open a Pull Request — even if it just contains a draft of the changes you’re planning, or a test that reproduces an issue — and we can discuss it further from there.

Download Details:

Author: Mikaoj
Source Code: 
License: MIT license

#swift #image #Picker 

BSImagePicker: A multiple image picker for iOS
Rupert  Beatty

Rupert Beatty


Gallery: Your Next Favorite Image and Video Picker


Your next favorite image and video picker


We all love image pickers, don't we? You may already know of ImagePicker, the all in one solution for capturing pictures and selecting images. Well, it has a sibling too, called Gallery. Based on the same engine that powers ImagePicker, Gallery has a clearer flow based on albums and focuses on the use case of selecting video. If this suits your need, give it a try 😉

Gallery has 3 tabs with easy navigation through swipe gesture

  • Images: select albums and images. Handle selection with hightlighted numbers so your users don't forget the order
  • Camera: your photographer skill goes here
  • Videos: display all videos and select. For now the use case is to select one video at a time

And, it has zero dependencies 😎



GalleryController is the main entry point, just instantiate and give it the delegate

let gallery = GalleryController()
gallery.delegate = self
present(gallery, animated: true, completion: nil)

The content controller is not loaded until the users navigate to, which offers a much faster experience.


The GalleryControllerDelegate requires you to implement some delegate methods in order to interact with the picker

func galleryController(_ controller: GalleryController, didSelectImages images: [Image])
func galleryController(_ controller: GalleryController, didSelectVideo video: Video)
func galleryController(_ controller: GalleryController, requestLightbox images: [Image])
func galleryControllerDidCancel(_ controller: GalleryController)

The lightbox delegate method is your chance to display selected images. If you're looking for a nice solution, here is the Lightbox that we use and love


The delegate methods give you Image and Video, which are just wrappers around PHAsset. To get the actual asset informations, we offer many convenient methods. See example


  • Use instance method resolve to get the actual UIImage
  • Use static method Image.resolve to resolve a list of images


  • Use instance method fetchDuration, fetchPlayerItem, fetchAVAsset, fetchThumbnail to get more information about the selected video.


Gallery handles permissions for you. It checks and askes for photo and camera usage permissions at first launch. As of iOS 10, we need to explicitly declare usage descriptions in plist files

<string>This app requires access to camera</string>
<string>This app requires access to photo library</string>


There are lots of customization points in Config structs. For example

Config.Permission.image = UIImage(named: ImageList.Gallery.cameraIcon)
Config.Font.Text.bold = UIFont(name: FontList.OpenSans.bold, size: 14)!
Config.Camera.recordLocation = true
Config.tabsToShow = [.imageTab, .cameraTab]

Video Editor

Gallery cares more about video with its editing functionalities. We have VideoEditor and AdvancedVideoEditor to trim, resize, scale and define quality of the selected video

func galleryController(_ controller: GalleryController, didSelectVideo video: Video) {
  controller.dismiss(animated: true, completion: nil)

  let editor = VideoEditor()
  editor.edit(video: video) { (editedVideo: Video?, tempPath: URL?) in
    DispatchQueue.main.async {
      if let tempPath = tempPath {
        let controller = AVPlayerViewController()
        controller.player = AVPlayer(url: tempPath)

        self.present(controller, animated: true, completion: nil)

With the Video object, you can fetchPlayerItem, fetchAVAsset and fetchThumbnail as well

And, of course, you have the ability to customize it

Config.VideoEditor.maximumDuration = 30
Config.VideoEditor.savesEditedVideoToLibrary = true


Gallery is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Gallery'

Gallery is also available through Carthage. To install just write into your Cartfile:

github "hyperoslo/Gallery"

Gallery can also be installed manually. Just download and drop Sources folders in your project.


We would love you to contribute to Gallery, check the CONTRIBUTING file for more info.

Download Details:

Author: Hyperoslo
Source Code: 
License: View license

#swift #ios #video #image

Gallery: Your Next Favorite Image and Video Picker
Rupert  Beatty

Rupert Beatty


Image Picker Controller for IOS Written in Swift 4 & 5


Image Picker Controller for IOS Written in Swift 4 & 5


DKImagePickerController is a highly customizable, Pure-Swift library.


  • Supports both single and multiple selection.
  • Supports filtering albums and sorting by type.
  • Supports landscape, iPad, and orientation switching.
  • iCloud Support.
  • Supports batch exports PHAsset to lcoal files.
  • Inline mode Support.
  • Customizable UICollectionViewLayout.
  • Customizable camera, photo gallery and photo editor.
  • Dark Mode Support


  • iOS 9.0+ (Drop support for iOS 8 in 4.3.0 or above)
  • ARC
  • Swift 4 & 5



iOS 9 and newer

DKImagePickerController is available on CocoaPods. Simply add the following line to your podfile:

# For latest release in cocoapods
pod 'DKImagePickerController'

For Swift 4.1

pod 'DKImagePickerController', :git => '', :branch => 'Swift4'

For iOS 8

pod 'DKImagePickerController', :git => '', :branch => 'iOS8'


There are 7 subspecs available now:

ImageDataManagerRequired. The subspec provides data to DKImagePickerController.
ResourceRequired. The subspec provides resource management and internationalization.
PhotoGalleryOptional. The subspec provides preview feature for PHAsset.
CameraOptional. The subspec provides camera feature.
InlineCameraOptional. The subspec should be pushed by UINavigationController, like UIImagePickerController with
PhotoEditorOptional. The subspec provides basic image editing features.

This means you can install only some of the DKImagePickerController modules. By default, you get all subspecs.
If you need to use your own photo editor, simply specify subspecs other than PhotoEditor:

pod 'DKImagePickerController', :subspecs => ['PhotoGallery', 'Camera', 'InlineCamera']

More information, see Extensions.


github "zhangao0086/DKImagePickerController"

If you use Carthage to build your dependencies, make sure you have added CropViewController.framework, DKCamera.framework, DKImagePickerController.framework, DKPhotoGallery.framework and SDWebImage.framework to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase.

Getting Started

Initialization and presentation

let pickerController = DKImagePickerController()

pickerController.didSelectAssets = { (assets: [DKAsset]) in

self.presentViewController(pickerController, animated: true) {}


#### Configurations

 /// Use UIDelegate to Customize the picker UI.
 @objc public var UIDelegate: DKImagePickerControllerBaseUIDelegate!
 /// Forces deselect of previous selected image. allowSwipeToSelect will be ignored.
 @objc public var singleSelect = false
 /// Auto close picker on single select
 @objc public var autoCloseOnSingleSelect = true
 /// The maximum count of assets which the user will be able to select, a value of 0 means no limit.
 @objc public var maxSelectableCount = 0
 /// Photos will be tagged with the location where they are taken.
 /// If true, your Info.plist should include the "Privacy - Location XXX" tag.
 open var containsGPSInMetadata = false
 /// Set the defaultAssetGroup to specify which album is the default asset group.
 public var defaultAssetGroup: PHAssetCollectionSubtype?
 /// Allow swipe to select images.
 @objc public var allowSwipeToSelect: Bool = false
 /// Allow select all
 @objc public var allowSelectAll: Bool = false
 /// A Bool value indicating whether the inline mode is enabled.
 @objc public var inline: Bool = false
 /// The type of picker interface to be displayed by the controller.
 @objc public var assetType: DKImagePickerControllerAssetType = .allAssets
 /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored.
 @objc public var sourceType: DKImagePickerControllerSourceType = .both
 /// A Bool value indicating whether allows to select photos and videos at the same time.
 @objc public var allowMultipleTypes = true
 /// A Bool value indicating whether to allow the picker auto-rotate the screen.
 @objc public var allowsLandscape = false
 /// Set the showsEmptyAlbums to specify whether or not the empty albums is shown in the picker.
 @objc public var showsEmptyAlbums = true
 /// A Bool value indicating whether to allow the picker shows the cancel button.
 @objc public var showsCancelButton = false
 /// The block is executed when the user presses the cancel button.
 @objc public var didCancel: (() -> Void)?
 /// The block is executed when the user presses the select button.
 @objc public var didSelectAssets: ((_ assets: [DKAsset]) -> Void)?
 /// The block is executed when the number of selected assets is changed.
 @objc public var selectedChanged: (() -> Void)?
 /// A Bool value indicating whether to allow the picker to auto-export the selected assets to the specified directory when done is called.
 /// picker will creating a default exporter if exportsWhenCompleted is true and the exporter is nil.
 @objc public var exportsWhenCompleted = false
 @objc public var exporter: DKImageAssetExporter?
 /// Indicates the status of the exporter.
 @objc public private(set) var exportStatus = DKImagePickerControllerExportStatus.none {
    willSet {
        if self.exportStatus != newValue {
            self.willChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus))
    didSet {
        if self.exportStatus != oldValue {
            self.didChangeValue(forKey: #keyPath(DKImagePickerController.exportStatus))
 /// The block is executed when the exportStatus is changed.
 @objc public var exportStatusChanged: ((DKImagePickerControllerExportStatus) -> Void)?
 /// The object that acts as the data source of the picker.
 @objc public private(set) lazy var groupDataManager: DKImageGroupDataManager

Inline Mode

let groupDataManagerConfiguration = DKImageGroupDataManagerConfiguration()
groupDataManagerConfiguration.fetchLimit = 10
groupDataManagerConfiguration.assetGroupTypes = [.smartAlbumUserLibrary]

let groupDataManager = DKImageGroupDataManager(configuration: groupDataManagerConfiguration)

self.pickerController = DKImagePickerController(groupDataManager: groupDataManager)
pickerController.inline = true
pickerController.UIDelegate = CustomInlineLayoutUIDelegate(imagePickerController: pickerController)
pickerController.assetType = .allPhotos
pickerController.sourceType = .photo

let pickerView = self.pickerController.view!
pickerView.frame = CGRect(x: 0, y: 170, width: self.view.bounds.width, height: 200)

Customizable UI

For example, see CustomUIDelegate.

Customizable Layout

For example, see CustomLayoutUIDelegate.

Conforms UIAppearance protocol

You can easily customize the appearance of the navigation bar using the appearance proxy.

UINavigationBar.appearance().titleTextAttributes = [
    NSFontAttributeName : UIFont(name: "Optima-BoldItalic", size: 21)!,
    NSForegroundColorAttributeName : UIColor.redColor()

Exporting to file

By default, the picker uses a singleton object of DKImageAssetExporter to export DKAsset to local files.

 Configuration options for a DKImageAssetExporter.  When an exporter is created,
 a copy of the configuration object is made - you cannot modify the configuration
 of an exporter after it has been created.
public class DKImageAssetExporterConfiguration: NSObject, NSCopying {
    @objc public var imageExportPreset = DKImageExportPresent.compatible
    /// videoExportPreset can be used to specify the transcoding quality for videos (via a AVAssetExportPreset* string).
    @objc public var videoExportPreset = AVAssetExportPresetHighestQuality
    #if swift(>=4.0)
    @objc public var avOutputFileType =
    @objc public var avOutputFileType = AVFileTypeQuickTimeMovie
    @objc public var exportDirectory = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("DKImageAssetExporter")

 A DKImageAssetExporter object exports DKAsset(PHAsset) from album (or iCloud) to the app's tmp directory (by default).
 It automatically deletes the exported directories when it receives a UIApplicationWillTerminate notification.
open class DKImageAssetExporter: DKBaseManager {
    /// This method starts an asynchronous export operation of a batch of asset.
    @objc public func exportAssetsAsynchronously(assets: [DKAsset], completion: ((_ info: [AnyHashable : Any]) -> Void)?) -> DKImageAssetExportRequestID

This exporter can automatically convert HEIF to JPEG:

public enum DKImageExportPresent: Int {
    compatible, // A preset for converting HEIF formatted images to JPEG.
    current     // A preset for passing image data as-is to the client.

You also can observe the export progress of each asset:

public protocol DKImageAssetExporterObserver {
    @objc optional func exporterWillBeginExporting(exporter: DKImageAssetExporter, asset: DKAsset)
    /// The progress can be obtained from the DKAsset.
    @objc optional func exporterDidUpdateProgress(exporter: DKImageAssetExporter, asset: DKAsset)
    /// When the asset's error is not nil, it indicates that an error occurred while exporting.
    @objc optional func exporterDidEndExporting(exporter: DKImageAssetExporter, asset: DKAsset)

extension DKAsset {
    /// The exported file will be placed in this location.
    /// All exported files can be automatically cleaned by the DKImageAssetDiskPurger when appropriate.
    @objc public var localTemporaryPath: URL?
    @objc public var fileName: String?
    /// Indicates the file's size in bytes.
    @objc public var fileSize: UInt
    /// If you export an asset whose data is not on the local device, and you have enabled downloading with the isNetworkAccessAllowed property, the progress indicates the progress of the download. A value of 0.0 indicates that the download has just started, and a value of 1.0 indicates the download is complete.
    @objc public var progress: Double
    /// Describes the error that occurred if the export has failed or been cancelled.
    @objc public var error: Error?

For example, see Export automatically and Export manually.


This picker uses DKImageExtensionController manages all extensions, you can register it with a DKImageBaseExtension and a specified DKImageExtensionType to customize camera, photo gallery and photo editor:

/// Registers an extension for the specified type.
public class func registerExtension(extensionClass: DKImageBaseExtension.Type, for type: DKImageExtensionType)

public class func unregisterExtension(for type: DKImageExtensionType)

The perform function will be called with a dictionary providing current context information when an extension is triggered:

/// Starts the extension.
func perform(with extraInfo: [AnyHashable: Any])

/// Completes the extension.
func finish()

The extraInfo will provide different information for different DKImageExtensionType:


let didFinishCapturingImage = extraInfo["didFinishCapturingImage"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
let didCancel = extraInfo["didCancel"] as? (() -> Void)

For a custom camera example, see CustomCameraExtension.


The extraInfo is the same as for Camera.

Photo Gallery

let groupId = extraInfo["groupId"] as? String
let presentationIndex = extraInfo["presentationIndex"] as? Int
let presentingFromImageView = extraInfo["presentingFromImageView"] as? UIImageView

Photo Editor

let image = extraInfo["image"] as? UIImage
let didFinishEditing = extraInfo["didFinishEditing"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
let metadata = extraInfo["metadata"] as? [AnyHashable : Any]

How to use in Objective-C

If you use CocoaPods

Add the following two lines into your Podfile:

pod 'DKImagePickerController'

Import the library into your Objective-C file:

#import <DKImagePickerController/DKImagePickerController-Swift.h>

If you use it directly in your project

See also:Swift and Objective-C in the Same Project

Drag and drop the DKCamera, DKImageManager and DKImagePickerController to your project

Import the library into your Objective-C file:

#import "YourProductModuleName-Swift.h"

then you can:

DKImagePickerController *pickerController = [DKImagePickerController new];

 [pickerController setDidSelectAssets:^(NSArray * __nonnull assets) {
 [self presentViewController:pickerController animated:YES completion:nil];


The default supported languages:

en, es, da, de, fr, hu, ja, ko, nb-NO, pt_BR, ru, tr, ur, vi, ar, it, zh-Hans, zh-Hant

You can also add a hook to return your own localized string:

DKImagePickerControllerResource.customLocalizationBlock = { title in
    if title == "" {
        return "Test(%@)"
    } else {
        return nil

or images:

DKImagePickerControllerResource.customImageBlock = { imageName in
    if imageName == "camera" {
        return DKImagePickerControllerResource.photoGalleryCheckedImage()
    } else {
        return nil

Contributing to this project

If you have feature requests or bug reports, feel free to help out by sending pull requests or by creating new issues.

Download Details:

Author: zhangao0086
Source Code: 
License: MIT license

#swift #picker #image 

Image Picker Controller for IOS Written in Swift 4 & 5

Image-optimizer: Easily Optimize Images using PHP

Easily optimize images using PHP

This package can optimize PNGs, JPGs, SVGs and GIFs by running them through a chain of various image optimization tools. Here's how you can use it:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();


The image at $pathToImage will be overwritten by an optimized version which should be smaller. The package will automatically detect which optimization binaries are installed on your system and use them.

Here are some example conversions that have been done by this package.

Loving Laravel? Then head over to the Laravel specific integration.

Using WordPress? Then try out the WP CLI command.


You can install the package via composer:

composer require spatie/image-optimizer

Optimization tools

The package will use these optimizers if they are present on your system:

Here's how to install all the optimizers on Ubuntu:

sudo apt-get install jpegoptim
sudo apt-get install optipng
sudo apt-get install pngquant
sudo npm install -g svgo@1.3.2
sudo apt-get install gifsicle
sudo apt-get install webp

And here's how to install the binaries on MacOS (using Homebrew):

brew install jpegoptim
brew install optipng
brew install pngquant
npm install -g svgo@1.3.2
brew install gifsicle
brew install webp

And here's how to install the binaries on Fedora/RHEL/CentOS:

sudo dnf install epel-release
sudo dnf install jpegoptim
sudo dnf install optipng
sudo dnf install pngquant
sudo npm install -g svgo@1.3.2
sudo dnf install gifsicle
sudo dnf install libwebp-tools

Which tools will do what?

The package will automatically decide which tools to use on a particular image.


JPGs will be made smaller by running them through JpegOptim. These options are used:

  • -m85: this will store the image with 85% quality. This setting seems to satisfy Google's Pagespeed compression rules
  • --strip-all: this strips out all text information such as comments and EXIF data
  • --all-progressive: this will make sure the resulting image is a progressive one, meaning it can be downloaded using multiple passes of progressively higher details.


PNGs will be made smaller by running them through two tools. The first one is Pngquant 2, a lossy PNG compressor. We set no extra options, their defaults are used. After that we run the image through a second one: Optipng. These options are used:

  • -i0: this will result in a non-interlaced, progressive scanned image
  • -o2: this set the optimization level to two (multiple IDAT compression trials)


SVGs will be minified by SVGO 1. SVGO's default configuration will be used, with the omission of the cleanupIDs plugin because that one is known to cause troubles when displaying multiple optimized SVGs on one page.

Please be aware that SVGO can break your svg. You'll find more info on that in this excellent blogpost by Sara Soueidan.

For now, the default configuration used for SVGO is only compatible with SVGO 1.x. To use options compatible with SVGO 2.x, you need to create your own optimization chain.


GIFs will be optimized by Gifsicle. These options will be used:

  • -O3: this sets the optimization level to Gifsicle's maximum, which produces the slowest but best results


WEBPs will be optimized by Cwebp. These options will be used:

  • -m 6 for the slowest compression method in order to get the best compression.
  • -pass 10 for maximizing the amount of analysis pass.
  • -mt multithreading for some speed improvements.
  • -q 90 Quality factor that brings the least noticeable changes.

(Settings are original taken from here)


This is the default way to use the package:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();


The image at $pathToImage will be overwritten by an optimized version which should be smaller.

The package will automatically detect which optimization binaries are installed on your system and use them.

To keep the original image, you can pass through a second argumentoptimize:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain->optimize($pathToImage, $pathToOutput);

In that example the package won't touch $pathToImage and write an optimized version to $pathToOutput.

Setting a timeout

You can set the maximum of time in seconds that each individual optimizer in a chain can use by calling setTimeout:


In this example each optimizer in the chain will get a maximum 10 seconds to do it's job.

Creating your own optimization chains

If you want to customize the chain of optimizers you can do so by adding Optimizers manually to an OptimizerChain.

Here's an example where we only want optipng and jpegoptim to be used:

use Spatie\ImageOptimizer\OptimizerChain;
use Spatie\ImageOptimizer\Optimizers\Jpegoptim;
use Spatie\ImageOptimizer\Optimizers\Pngquant;

$optimizerChain = (new OptimizerChain)
   ->addOptimizer(new Jpegoptim([

   ->addOptimizer(new Pngquant([

Notice that you can pass the options an Optimizer should use to its constructor.

Writing a custom optimizers

Want to use another command line utility to optimize your images? No problem. Just write your own optimizer. An optimizer is any class that implements the Spatie\ImageOptimizer\Optimizers\Optimizer interface:

namespace Spatie\ImageOptimizer\Optimizers;

use Spatie\ImageOptimizer\Image;

interface Optimizer
     * Returns the name of the binary to be executed.
     * @return string
    public function binaryName(): string;

     * Determines if the given image can be handled by the optimizer.
     * @param \Spatie\ImageOptimizer\Image $image
     * @return bool
    public function canHandle(Image $image): bool;

     * Set the path to the image that should be optimized.
     * @param string $imagePath
     * @return $this
    public function setImagePath(string $imagePath);

     * Set the options the optimizer should use.
     * @param array $options
     * @return $this
    public function setOptions(array $options = []);

     * Get the command that should be executed.
     * @return string
    public function getCommand(): string;

If you want to view an example implementation take a look at the existing optimizers shipped with this package.

You can easily add your optimizer by using the addOptimizer method on an OptimizerChain.

use Spatie\ImageOptimizer\ImageOptimizerFactory;

$optimizerChain = OptimizerChainFactory::create();

   ->addOptimizer(new YourCustomOptimizer())

Logging the optimization process

By default the package will not throw any errors and just operate silently. To verify what the package is doing you can set a logger:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

   ->useLogger(new MyLogger())

A logger is a class that implements Psr\Log\LoggerInterface. A good logging library that's fully compliant is Monolog. The package will write to log which Optimizers are used, which commands are executed and their output.

Example conversions

Here are some real life example conversions done by this package.


Original: Photoshop 'Save for web' | PNG-24 with transparency
40 KB


16 KB (40%)



Original: Photoshop 'Save for web' | quality 60, optimized
547 KB


525 KB (95%)


credits: Jeff Sheldon, via Unsplash


Original: Illustrator | Web optimized SVG export
26 KB


20 KB (76%)



Original: WebPonize
528 KB


328 KB (89%)


credits: Jeff Sheldon, via Unsplash


Please see CHANGELOG for more information what has changed recently.


composer test


Please see CONTRIBUTING for details.


If you've found a bug regarding security please mail instead of using the issue tracker.


You're free to use this package (it's MIT-licensed), but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.


This package has been inspired by psliwa/image-optimizer

Emotional support provided by Joke Forment

Download Details:

Author: Spatie
Source Code: 
License: MIT license

#php #performance #image #png 

Image-optimizer: Easily Optimize Images using PHP
Rupert  Beatty

Rupert Beatty


ImageSlideshow: Swift Image Slideshow with Circular Scrolling, Timer

🖼 ImageSlideshow

Customizable Swift image slideshow with circular scrolling, timer and full screen viewer

📱 Example

To run the example project, clone the repo, and run pod install from the Example directory first.

🔧 Installation


ImageSlideshow is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'ImageSlideshow', '~> 1.9.0'


To integrate ImageSlideshow into your Xcode project using Carthage, specify it in your Cartfile:

github "zvonicek/ImageSlideshow" ~> 1.9.0

Carthage does not include InputSources for external providers (due to dependency on those providers) so you need to grab the one you need from ImageSlideshow/Classes/InputSources manually.


One possibility is to download a built framework ( from releases page and link it with your project (underLinked Frameworks and Libraries in your target). This is, however, currently problematic because of rapid Swift development -- the framework is built for a single Swift version and may not work on previous/future versions.

Alternatively can also grab the whole ImageSlideshow directory and copy it to your project. Be sure to remove those external Input Sources you don't need.

Note on Swift 2.3, Swift 3 and Swift 4 support

Version 1.4 supports Swift 4. Swift 3 is supported from version 1.0, for Swift 2.2 and Swift 2.3 compatible code use version 0.6 or branch swift-2.3.

🔨 How to use

Add ImageSlideshow view to your view hiearchy either in Interface Builder or in code.

Loading images

Set images by using setImageInputs method on ImageSlideshow instance with an array of InputSources. By default you can use ImageSource which takes UIImage or few other InputSources for most popular networking libraries. You can also create your own input source by implementing InputSource protocol.

LibraryInputSource namePod
AlamofireImageAlamofireSourcepod "ImageSlideshow/Alamofire"
AFNetworkingAFURLSourcepod "ImageSlideshow/AFURL"
SDWebImageSDWebImageSourcepod "ImageSlideshow/SDWebImage"
KingfisherKingfisherSourcepod "ImageSlideshow/Kingfisher"
ParseParseSourcepod "ImageSlideshow/Parse"
  ImageSource(image: UIImage(named: "myImage"))!,
  ImageSource(image: UIImage(named: "myImage2"))!,
  AlamofireSource(urlString: ""),
  KingfisherSource(urlString: ""),
  ParseSource(file: PFFile(name:"image.jpg", data:data))


Behaviour is configurable by those properties:

  • slideshowInterval - slideshow interval in seconds (default 0 – disabled)
  • zoomEnabled - enables zooming (default false)
  • circular - enables circular scrolling (default true)
  • activityIndicator – allows to set custom activity indicator, see Activity indicator section
  • pageIndicator – allows to set custom page indicator, see Page indicator section; assign nil to hide page indicator
  • pageIndicatorPosition - configures position of the page indicator
  • contentScaleMode - configures the scaling (default ScaleAspectFit)
  • draggingEnabled - enables dragging (default true)
  • currentPageChanged - closure called on page change
  • willBeginDragging - closure called on scrollViewWillBeginDragging
  • didEndDecelerating - closure called on scrollViewDidEndDecelerating
  • preload - image preloading configuration (default all preloading, also fixed)

Page Indicator

Page indicator can be customized using the pageIndicator property on ImageSlideshow. By defualt, a plain UIPageControl is used. If needed, page control can be customized:

let pageIndicator = UIPageControl()
pageIndicator.currentPageIndicatorTintColor = UIColor.lightGray
pageIndicator.pageIndicatorTintColor =
slideshow.pageIndicator = pageIndicator

Also, a simple label page indicator that shows pages in style "5/21" (fifth page from twenty one) is provided:

slideshow.pageIndicator = LabelPageIndicator()

You can also use your own page indicator by adopting the PageIndicatorView protocol.

Position of the page indicator can be configured by assigning a PageIndicatorPosition value to the pageIndicatorPosition property on ImageSlideshow. You may specify the horizontal and vertical positioning separately.

Horizontal positioning options are: .left(padding: Int), .center, .right(padding: Int)

Vertical positioning options are: .top, .bottom, .under, customTop(padding: Int), customBottom(padding: Int), customUnder(padding: Int)


slideshow.pageIndicatorPosition = PageIndicatorPosition(horizontal: .left(padding: 20), vertical: .bottom)

Activity Indicator

By default activity indicator is not shown, but you can enable it by setting DefaultActivityIndicator instance to Image Slideshow:

slideshow.activityIndicator = DefaultActivityIndicator()

You can customize style and color of the indicator:

slideshow.activityIndicator = DefaultActivityIndicator(style: .white, color: nil)

There's also an option to use your own activity indicator. You just need to implement ActivityIndicatorView and ActivityIndicatorFactory protocols. See ActivityIndicator.swift for more information.

Full Screen view

There is also a possibility to open full-screen image view using attached FullScreenSlideshowViewController. The simplest way is to call:

override func viewDidLoad() {
  let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.didTap))

func didTap() {
  slideshow.presentFullScreenController(from: self)

FullScreenSlideshowViewController can also be instantiated and configured manually if more advanced behavior is needed.

👀 References

Inspired by projects:

Download Details:

Author: Zvonicek
Source Code: 
License: MIT license

#swift #ios #gallery #image 

ImageSlideshow: Swift Image Slideshow with Circular Scrolling, Timer

Image Picker Tutorial in Flutter


A new flutter plugin project.

Getting Started

This project is a starting point for a Flutter plug-in package, a specialized package that includes platform-specific implementation code for Android and/or iOS.

For help getting started with Flutter, view our online documentation, which offers tutorials, samples, guidance on mobile development, and a full API reference. 

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_timpage_picker

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

  flutter_timpage_picker: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_timpage_picker/flutter_timpage_picker.dart'; 


import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:flutter_timpage_picker/flutter_timpage_picker.dart';
import 'package:flutter_timpage_picker/image_picker_option.dart';

void main() {
  runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  State<MyApp> createState() => _MyAppState();

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';

  void initState() {

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion = await FlutterTimpagePicker.platformVersion ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;

  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        body: Center(
            child: Column(
          children: [
            Text('Running on: $_platformVersion\n'),
              onPressed: () async {
                PickOptions options = PickOptions();
                options.imageCount = 1;
                options.isCrop = false;
                options.isCamera = false;
                options.showSelectedIndex = false;
                options.isRecordSelected = true;
                var ret = await FlutterTimpagePicker.showImagePicker(options);
                print("result:" + ret.toString());
              child: Text("选择照片"),
              onPressed: () async {
                PickOptions options = PickOptions();
                options.imageCount = 1;
                options.isCrop = true;
                options.isCamera = false;
                options.showSelectedIndex = false;
                options.isRecordSelected = true;
                var ret = await FlutterTimpagePicker.openCamera(options);
                if (ret == null) {
                  print("camera null");
                } else {
                  print("camera result:" + ret.toString());
              child: Text("拍照"),

Download Details:


Source Code:

#flutter #image #Picker 

Image Picker Tutorial in Flutter