• Stars
    star
    111
  • Rank 314,510 (Top 7 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swift wrapper around ImageIO

ImageIO.Swift

CI Status Version License Platform

ImageIO.Swift makes working with images on Apple platforms easy. It's SDWebImage, FLAnimatedImage and Concorde all in one!

  • Download images asychronously.
  • Animate GIFs, PNGs and (in iOS 13) HEICs!
  • Incrementally load interlaced and progressive JPEGs.
  • Generate thumbnails directly from the file (especially useful for HEIC images because they often embed pre-rendered thumbnails).
  • Examine image details and exif metadata.

Usage

UIKit (ImageIOUIKit)

ImageSourceView handles loading and displaying images.

// display an image downloaded from a URL
let view = ImageSourceView()
view.isAnimationEnabled = true
view.load(url)

If an image url is shown in multiple places on the same screen (like a single users profile picture on a news feed layout) it will only be downloaded and loaded into memory once. It will also be intelligently cached so that subsequent requests will re-use memory and downloaded data.

You can also set an image source directly:

let view = ImageSourceView()
view.isAnimationEnabled = true
view.imageSource = imageSource

You can access the views imageSource (regardless of whether you set it directly or loaded it from a url) and subscribe to it's didUpdateData notification to track it's download. To get updates for different animation frames, you can either subclass ImageSourceView or use KVO with displayedImage.

The UIKit module also includes extensions on ImageSource to access UIImages that are correctly orriented (a feature that CGImage doesn't account for).

Experimental: SwiftUI (ImageIOSwiftUI)

Works with iOS, macOS, watchOS and tvOS!

URLImageSourceView works a lot like an img tag in html.

// display an image downloaded from a URL
URLImageSourceView(
	url: url, 
	isAnimationEnabled: true,
	label: Text("Alt text")
)

If an image url is shown in multiple places on the same screen (like a single user's profile picture on a news feed layout) it will only be downloaded and loaded into memory once. It will also be intelligently cached so that subsequent requests will re-use memory and downloaded data.

If you want to load an image source separately, you can use ImageSourceView:

// display an image source, animating if possible
ImageSourceView(
	imageSource: imageSource,
	isAnimationEnabled: true,
	label: Text("Alt text")
)

Finally, if you want to customize how an image is rendered, you can provide your own content to either URLImageSourceView or ImageSourceView:

// places an animation progress bar at the bottom of the image
URLImageSourceView(
	url: url,
	isAnimationEnabled: true,
	label: Text("Alt text")
) { imageSource, animationFrame, label in
	StaticImageSourceView(imageSource: imageSource, animationFrame: animationFrame, label: label)
		.aspectRatio(contentMode: .fit)
		.overlay(
			Rectangle()
				.fill(Color.blue.opacity(0.5))
				.frame(height: 10)
				.relativeWidth(Length(imageSource.progress(atFrame: animationFrame))),
			alignment: .bottomLeading
		)
}

The content callback is called every time image data is updated or an animation frame changes. By default, StaticImageSourceView is used to display an image frame, and you can use it as a base for your customization.

If you want to provide a placeholder while the image loads, the recommended way to do that is with a ZStack:

// load an image, clipped by a circle with a gray background and placeholder image
ZStack {
	Image(systemName: "person.fill")
		.foregroundColor(Color(white: 0.4))
	URLImageSourceView(url: user.picture.medium)
		.frame(width: 36, height: 36)
}
.frame(width: 36, height: 36)
.background(Color(white: 0.8))
.clipShape(Circle())

This way images that load incrementally will be shown as they load.

Disclaimer: I had hoped that SwiftUI would become more stable over the Summer, but it is still quit buggy and incomplete. While I don't know of any issues with this projects SwiftUI support, I am not using SwiftUI in any of my projects, and consequently cannot vouch for the stability of this project.

ImageSource

You can think of CG/NS/UIImage as a single frame of pixels. ImageSource sits a level below that, providing access to almost anything an image file provides, including metadata and multiple representations. For instance, animated images have multiple image frames as well as timing metadata.

You can access things like count (the number of frames in an animated image) or typeIdentifier to get the kind of file it is. But it's primary use is to generate images:

imageSource.cgImage(at: 3) // frame 3
// with UIKit integration:
imageSource.image(at: 3)

You can provide options on how the image gets generated.

// decode the image data immediately instead of lazily when it gets drawn for the first time
// this is especially useful if you're loading images in a background thread before passing them to the main thread
var options = ImageSource.ImageOptions()
options.shouldDecodeImmediately = false
imageSource.cgImage(options: options)

Creating thumbnails is similar:

imageSource.cgThumbnailImage(size: thumbnailSize, mode: .fill)

Note that image sources don't support cropping, so it will always return an image with the same aspect ratio as the original. If the image contains an embed thumbnail, this can be quit faster than normal thumnail rendering.

Because images sources can reference a file on disk, you can load metadata for an image without loading the entire file into memory. This is especially useful for getting an images size.

ImageSource(url: fileURL).properties(at: 0)?.imageSize

Note that if the image source is being loaded incrementally or references an invalid file, the size will be nil.

Example

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

Installation

Swift Package Manager

In Xcode 11 you can add ImageIOSwift as a package in your project settings using the Github URL of the project. You can then link to the packages you need (ImageIOSwift, ImageIOSwiftUI or ImageIOUIKit).

On macOS, you can use is on the command line by adding the following to your Package.swift:

dependencies: [
	.package(url: "https://github.com/davbeck/ImageIOSwift.git", from: "0.5.0"),
],

Note that because ImageIO is not available on Linux (or any non-Apple platform) that this package cannot be used there.

CocoaPods

Add the following line to your Podfile:

pod 'ImageIOSwift'
# one of both of these
pod 'ImageIOSwiftUI'
pod 'ImageIOUIKit'

License

ImageIOSwift is available under the MIT license. See the LICENSE file for more info.

Sample Image Sources

More Repositories

1

TURecipientBar

A UIView to handle entering recipients similar to iOS Mail
Objective-C
339
star
2

TUSafariActivity

A UIActivity subclass that opens URLs in Safari
Objective-C
312
star
3

CacheKit

Simple and flexible caching mechanism for in memory and persistent caches.
Objective-C
191
star
4

iPhone-Simulator-Capture

Records video screen captures of the iPhone simulator
Objective-C
120
star
5

swift-glob

A native Swift implementation of glob match patterns.
Swift
45
star
6

MultipartForm

The missing multipart form support for URLSession.
Swift
44
star
7

PG.swift

A PostgreSQL client library written in pure Swift (without any dependency the C libpq).
Objective-C
42
star
8

graphile-scheduler

Job scheduling for PostgreSQL running on Node.js built on top of graphile-worker. It’s like cron, but reliable and distributed.
TypeScript
39
star
9

TULayoutAdditions

Shortcuts and helper methods for iOS Auto Layout
Objective-C
26
star
10

TNKImagePickerController

A replacement for UIImagePickerController that can select multiple photos.
Objective-C
24
star
11

TNKRefreshControl

A replacement for UIRefreshControl with a more modern look and more flexibility
Objective-C
20
star
12

SimpleInstapaperKit

An iOS interface for the Instapaper Simple API (http://www.instapaper.com/api/simple)
Objective-C
11
star
13

RefreshTintFail

UIRefreshControl tintColor is not applied on initial refresh
Objective-C
9
star
14

plaza-ios

An iOS App to view public topics, events, needs, prayers and albums from On The City Plaza.
Objective-C
8
star
15

TULogging

Better logging that uses ASL log levels. Based on work by Mike Weller.
Objective-C
7
star
16

PersistentCacheKit

A Swift package for caching items to the filesystem (using SQLite by default).
Swift
7
star
17

UntitledTerminalApp

Swift
6
star
18

DBF-Reader

A simple dbf editor for Mac.
C
5
star
19

version_bot

A simple service to keep track of build numbers.
Ruby
3
star
20

iphone-icon-tester

Preview your iPhone icons natively.
PHP
2
star
21

TNKFoundation

A collection of small utilities in Swift.
Swift
2
star
22

AsyncKit

Swift
2
star
23

GoogleVoiceBrowser

A simple dedicated browser window for Google Voice
Objective-C
2
star
24

LoginExample

An example of how to create a login flow for iOS. See https://www.davidbeck.co/blog/2018/08/03/login-app-flow.html.html
Swift
2
star
25

RoutesExample

Example app of how to use url based navigation for an iOS app. For more information see https://www.davidbeck.co/blog/2018/08/17/route-base-navigation.html.html
Swift
2
star
26

TNKData

A replacement for Core Data with a focus on control, performance and concurrency
Objective-C
1
star
27

CacheExample

Example code to demonstrate a bug in NSURLCache
Objective-C
1
star
28

davbeck.github.io

Static site for davidbeck.co
SCSS
1
star
29

VectorIO

Swift
1
star
30

deploy_hook

Automatically run a deploy script when changes are pushed to Github.
JavaScript
1
star
31

aws-lambda-swift-hook

A Swift module to facilitate running Swift on Lambda using a node bootstrap.
Swift
1
star
32

GIFFun

A sample project demonstrating how to support animated GIFs.
Swift
1
star
33

versionbotclient

Go
1
star
34

sawdust.fun

SCSS
1
star
35

monkey_proxy

A proxy server that records and replays http requests.
JavaScript
1
star
36

xcassetsenum

Convert an Xcode xcassets catalog file into a Swift enum for type safe compiler checked image assets.
Go
1
star
37

radars

Various bug reports sent to Apple with sample code
1
star
38

SwiftRecord

Object-relational mapping in Swift
Swift
1
star
39

TUMessagePackSerialization

MessagePack serializer for Objective-C and Swift
Objective-C
1
star
40

chipins

A Wordpress plugin that adds a short code to show giving progress.
PHP
1
star
41

cdmodeltoswift

Custom Swift codegen for Core Data models.
Swift
1
star
42

SyphonToHLS

A simple app that converts Syphon streams to HLS
Objective-C
1
star