Image

Image

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

1669471680

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:

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

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: https://sebhastian.com/

#javascript #html #image 

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

Monty Boehm

1669440125

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 document.body.style.backgroundImage:

document.body.style.backgroundImage = "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:

document.body.style.backgroundImage = "url('./assets/image.png')";

Or go up one folder with the following relative path:

document.body.style.backgroundImage = "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:

document.body.style.backgroundImage =
  "url('https://sebhastian.com/img/default.png')";

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:

document.body.style.backgroundImage =
  "url('https://sebhastian.com/img/default.png')";

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:

document.body.style.backgroundRepeat = "no-repeat";
document.body.style.backgroundSize = "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">
  <head>
    <meta charset="utf-8" />
    <title>JavaScript change background image</title>
    <script>
      // The function below will change the background image
      function changeBackgroundImage() {
        document.body.style.backgroundImage = "url('image.png')";
        document.body.style.backgroundRepeat = "no-repeat";
        document.body.style.backgroundSize = "cover";
      }
    </script>
  </head>
  <body>
    <h1>Click the button to change the background image:</h1>
    <button onclick="changeBackgroundImage();">Change</button>
  </body>
</html>

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">
  <head>
    <meta charset="utf-8" />
    <title>JavaScript change background image</title>
    <script>
      // The function below will change the background image
      function changeBackgroundImage() {
        document.body.style.backgroundImage = "url('image.png')";
      }
      // call the function when the whole DOM content is loaded
      document.addEventListener("DOMContentLoaded", changeBackgroundImage());
    </script>
  </head>
  <body>
    <h1>Change the background image on load</h1>
  </body>
</html>

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">
  <head>
    <meta charset="utf-8" />
    <title>JavaScript change background image</title>
    <script>
      // change the background image of div user
      function changeBackgroundUser() {
        document.getElementById("user").style.backgroundImage =
          "url('image.png')";
      }
    </script>
  </head>
  <body>
    <div id="user">
      <h1>Change specific DIV background image</h1>
    </div>
    <div id="guest">
      <h2>This element's parent DIV background won't be changed</h2>
    </div>
    <div id="stranger">
      <h2>Neither this one</h2>
    </div>
    <button onclick="changeBackgroundUser();">Change BG image</button>
  </body>
</html>

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:

<script>
  // change the background image using the passed parameter
  function changeBackgroundImage(bgImage) {
    document.body.style.backgroundImage = "url(" + bgImage + ")";
  }
</script>

<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: https://sebhastian.com/

#javascript #webpage #image 

How to Changing Webpage Background Image using JavaScript Code
Sheldon  Grant

Sheldon Grant

1669278904

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:

<body>
  <canvas
    id="emptyCanvas"
    width="300"
    height="300"
  ></canvas>
  <script>
    let canvas = document.getElementById("emptyCanvas");
    let ctx = canvas.getContext("2d");
    ctx.fillStyle = "blue";
    ctx.fillRect(50, 100, 150, 150);
  </script>
</body>

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();
console.log(dataURL);

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:

data:image/png;base64,
iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAALBElEQ...
ooAghcEBCsC6puIoDACQHBOsHqKAIIXBAQrAuqbiKAwAmBP7PLLTzDQluOAAAAAElFTkSuQmCC

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: https://sebhastian.com/

#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;

document.body.appendChild(image);

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

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

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">
document.body.appendChild(image);

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: https://sebhastian.com/

#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: https://sebhastian.com/

#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: https://sebhastian.com/

#jquery #background #image 

How to Adding Background Image using jQuery
Nat  Grady

Nat Grady

1668030780

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.

Documentation

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.

library(magick)
frink <- image_read("https://jeroen.github.io/images/frink.png")
image_trim(frink)
image_scale(frink, "200x200")
image_flip(frink)
image_rotate(frink, 45) ## <-- result of this is shown
image_negate(frink)
frink %>% 
  image_background("green") %>% 
  image_flatten() %>%
  image_border("red", "10x10")
image_rotate(frink, 45) %>% image_write("man/figures/frink-rotated.png")

Effects

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

Create GIF animation:

# Download images
oldlogo <- image_read("https://developer.r-project.org/Logo/Rlogo-2.png")
newlogo <- image_read("https://jeroen.github.io/images/Rlogo-old.png")
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")
anim2.gif

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

earth <- image_read("https://upload.wikimedia.org/wikipedia/commons/2/2c/Rotating_earth_%28large%29.gif")
length(earth)
earth[1]
earth[1:3]
earth1 <- rev(image_flip(earth)) ## How Austrialans see earth
image_write(earth1, "man/figures/earth1.gif") ## <-- result of this is shown
earth1.gif

R logo with dancing banana

logo <- image_read("https://www.r-project.org/logo/Rlogo.png")
banana <- image_read("https://jeroen.github.io/images/banana.gif")
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")
Rlogo-banana.gif

Use magick in Shiny Apps

This demo application shows how to use magick with shiny: https://github.com/jeroen/shinymagick

Installation

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

install.packages("magick")

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: https://github.com/ropensci/magick 
License: View license

#r #image #processing #rstats 

Magick: Magic, Madness, Heaven, Sin
Royce  Reinger

Royce Reinger

1668000480

Caire: Content Aware Image Resize Library

Caire

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
originalsobeldebug

Features

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

Install

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

$ go install github.com/esimov/caire/cmd/caire@latest 

MacOS (Brew) install

The library can also be installed via Homebrew.

$ brew install caire

Usage

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

Supported commands:

$ caire --help

The following flags are supported:

FlagDefaultDescription
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 (https://github.com/esimov/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 (https://gioui.org/#installation) .

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

Results

Shrunk images

OriginalShrunk
broadway_tower_editbroadway_tower_edit
waterfallwaterfall
dubaidubai
boatboat

Enlarged images

OriginalExtended
gasadalurgasadalur
dubaidubai

Useful resources

Download Details:

Author: esimov
Source Code: https://github.com/esimov/caire 
License: MIT license

#machinelearning #golang #computervision #image 

Caire: Content Aware Image Resize Library
Rupert  Beatty

Rupert Beatty

1667803380

An Easy to Use Image Viewer That Is inspired By Facebook

ImageViewer.swift

An easy to use Image Viewer that is inspired by Facebook

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

Supports

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

Installation

CocoaPods

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

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()

imageView.setupImageViewer()

Example:

import ImageViewer_swift

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

Or you might load it from a URL

imageView.setupImageViewer(url: URL(string: "https://example.com/image.jpg")!)

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: "https://example.com/your-image-1.jpg")!,
    URL(string: "https://example.com/your-image-2.jpg")!,
    URL(string: "https://example.com/your-image-3.jpg")!
]
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

http://www.iamkel.net

Dependency

Download Details:

Author: Michaelhenry
Source Code: https://github.com/michaelhenry/ImageViewer.swift 
License: 

#swift #image #ios #gallery #library 

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

Rupert Beatty

1667799426

BSImagePicker: A multiple image picker for iOS

BSImagePicker

A multiple image picker for iOS.

Features

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

Usage

Info.plist

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

<key>NSPhotoLibraryUsageDescription</key>
<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.
})

PHAsset

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.

Installation

Cocoapods

Add the following line to your Podfile:

pod "BSImagePicker", "~> 3.1"

Carthage

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: "https://github.com/mikaoj/BSImagePicker.git", from: "version-tag")
]

Xamarin

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

Contribution

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: https://github.com/mikaoj/BSImagePicker 
License: MIT license

#swift #image #Picker 

BSImagePicker: A multiple image picker for iOS
Rupert  Beatty

Rupert Beatty

1667594340

Gallery: Your Next Favorite Image and Video Picker

Gallery 

Your next favorite image and video picker

Description

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 😎

Usage

Presenting

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.

Delegate

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

Resolving

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

Image

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

Video

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

Permission

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

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

Configuration

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

Installation

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.

Contributing

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

Download Details:

Author: Hyperoslo
Source Code: https://github.com/hyperoslo/Gallery 
License: View license

#swift #ios #video #image

Gallery: Your Next Favorite Image and Video Picker
Rupert  Beatty

Rupert Beatty

1667570340

Image Picker Controller for IOS Written in Swift 4 & 5

DKImagePickerController

Image Picker Controller for IOS Written in Swift 4 & 5

Description

DKImagePickerController is a highly customizable, Pure-Swift library.

Features

  • 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

Requirements

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

Installation

CocoaPods

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 => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'Swift4'

For iOS 8

pod 'DKImagePickerController', :git => 'https://github.com/zhangao0086/DKImagePickerController.git', :branch => 'iOS8'

Subspecs

There are 7 subspecs available now:

SubspecDescription
CoreRequired.
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 UIImagePickerControllerSourceType.camera.
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.

Carthage

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
    print("didSelectAssets")
    print(assets)
}

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

​````

#### Configurations

​```swift
 /// 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))
            
            self.exportStatusChanged?(self.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)
self.view.addSubview(pickerView)

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.
 */
@objc
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 = AVFileType.mov
    #else
    @objc public var avOutputFileType = AVFileTypeQuickTimeMovie
    #endif
    
    @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.
 */
@objc
open class DKImageAssetExporter: DKBaseManager {
    
    /// This method starts an asynchronous export operation of a batch of asset.
    @discardableResult
    @objc public func exportAssetsAsynchronously(assets: [DKAsset], completion: ((_ info: [AnyHashable : Any]) -> Void)?) -> DKImageAssetExportRequestID
}

This exporter can automatically convert HEIF to JPEG:

@objc
public enum DKImageExportPresent: Int {
    case
    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:

@objc
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.

Extensions

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:

Camera

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

For a custom camera example, see CustomCameraExtension.

InlineCamera

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'
use_frameworks!

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) {
     NSLog(@"didSelectAssets");
 }];
 
 [self presentViewController:pickerController animated:YES completion:nil];

Localization

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 == "picker.select.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: https://github.com/zhangao0086/DKImagePickerController 
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();

$optimizerChain->optimize($pathToImage);

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.

Installation

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

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

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

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

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

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)

Usage

This is the default way to use the package:

use Spatie\ImageOptimizer\OptimizerChainFactory;

$optimizerChain = OptimizerChainFactory::create();

$optimizerChain->optimize($pathToImage);

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:

$optimizerChain
    ->setTimeout(10)
    ->optimize($pathToImage);

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([
       '--strip-all',
       '--all-progressive',
   ]))

   ->addOptimizer(new Pngquant([
       '--force',
   ]))

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();

$optimizerChain
   ->addOptimizer(new YourCustomOptimizer())
   ->optimize($pathToImage);

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();

$optimizerChain
   ->useLogger(new MyLogger())
   ->optimize($pathToImage);

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.

png

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

Original

Optimized
16 KB (40%)

Optimized

jpg

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

Original

Optimized
525 KB (95%)

Optimized

credits: Jeff Sheldon, via Unsplash

svg

Original: Illustrator | Web optimized SVG export
26 KB

Original

Optimized
20 KB (76%)

Optimized

webp

Original: WebPonize
528 KB

Original

Optimized
328 KB (89%)

Optimized

credits: Jeff Sheldon, via Unsplash

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

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

Postcardware

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.

Credits

This package has been inspired by psliwa/image-optimizer

Emotional support provided by Joke Forment

Download Details:

Author: Spatie
Source Code: https://github.com/spatie/image-optimizer 
License: MIT license

#php #performance #image #png 

Image-optimizer: Easily Optimize Images using PHP
Rupert  Beatty

Rupert Beatty

1667299140

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

CocoaPods

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

pod 'ImageSlideshow', '~> 1.9.0'

Carthage

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.

Manually

One possibility is to download a built framework (ImageSlideshow.framework.zip) 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"
slideshow.setImageInputs([
  ImageSource(image: UIImage(named: "myImage"))!,
  ImageSource(image: UIImage(named: "myImage2"))!,
  AlamofireSource(urlString: "https://images.unsplash.com/photo-1432679963831-2dab49187847?w=1080"),
  KingfisherSource(urlString: "https://images.unsplash.com/photo-1432679963831-2dab49187847?w=1080"),
  ParseSource(file: PFFile(name:"image.jpg", data:data))
])

Configuration

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 = UIColor.black
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)

Example:

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))
  slideshow.addGestureRecognizer(gestureRecognizer)
}

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: https://github.com/zvonicek/ImageSlideshow 
License: MIT license

#swift #ios #gallery #image 

ImageSlideshow: Swift Image Slideshow with Circular Scrolling, Timer

Image Picker Tutorial in Flutter

flutter_timpage_picker

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):

dependencies:
  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'; 

example/lib/main.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);

  @override
  State<MyApp> createState() => _MyAppState();
}

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

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 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;
    });
  }

  @override
  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'),
            ElevatedButton(
              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("选择照片"),
            ),
            ElevatedButton(
              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:

Author: 

Source Code: https://pub.dev/packages/flutter_timpage_picker

#flutter #image #Picker 

Image Picker Tutorial in Flutter