• Stars
    star
    3,998
  • Rank 10,421 (Top 0.3 %)
  • Language
    C
  • License
    Apache License 2.0
  • Created almost 9 years ago
  • Updated 16 days ago

Reviews

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

Repository Details

A thread safe, performant, feature rich image fetcher

PINRemoteImage

Fast, non-deadlocking parallel image downloader and cache for iOS

CocoaPods compatible Carthage compatible Build status

PINRemoteImageManager is an image downloading, processing and caching manager. It uses the concept of download and processing tasks to ensure that even if multiple calls to download or process an image are made, it only occurs one time (unless an item is no longer in the cache). PINRemoteImageManager is backed by GCD and safe to access from multiple threads simultaneously. It ensures that images are decoded off the main thread so that animation performance isn't affected. None of its exposed methods allow for synchronous access. However, it is optimized to call completions on the calling thread if an item is in its memory cache.

PINRemoteImage supports downloading many types of files. It, of course, supports both PNGs and JPGs. It also supports decoding WebP images if Google's library is available. It even supports GIFs and Animated WebP via PINAnimatedImageView.

PINRemoteImage also has two methods to improve the experience of downloading images on slow network connections. The first is support for progressive JPGs. This isn't any old support for progressive JPGs though: PINRemoteImage adds an attractive blur to progressive scans before returning them.

Progressive JPG with Blur

PINRemoteImageCategoryManager defines a protocol which UIView subclasses can implement and provide easy access to PINRemoteImageManager's methods. There are built-in categories on UIImageView, PINAnimatedImageView and UIButton, and it's very easy to implement a new category. See [UIImageView+PINRemoteImage](/Pod/Classes/Image Categories/UIImageView+PINRemoteImage.h) of the existing categories for reference.

Download an image and set it on an image view:

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[imageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/kitten.jpg"]];

Swift

let imageView = UIImageView()
imageView.pin_setImage(from: URL(string: "https://pinterest.com/kitten.jpg")!)

Download a progressive jpeg and get attractive blurred updates:

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[imageView setPin_updateWithProgress:YES];
[imageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/progressiveKitten.jpg"]];

Swift

let imageView = UIImageView()
imageView.pin_updateWithProgress = true
imageView.pin_setImage(from: URL(string: "https://pinterest.com/progressiveKitten.jpg")!)

Download a WebP file

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[imageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/googleKitten.webp"]];

Swift

let imageView = UIImageView()
imageView.pin_setImage(from: URL(string: "https://pinterest.com/googleKitten.webp")!)

Download a GIF and display with PINAnimatedImageView

Objective-C

PINAnimatedImageView *animatedImageView = [[PINAnimatedImageView alloc] init];
[animatedImageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/flyingKitten.gif"]];

Swift

let animatedImageView = PINAnimatedImageView()
animatedImageView.pin_setImage(from: URL(string: "http://pinterest.com/flyingKitten.gif")!)

Download and process an image

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[self.imageView pin_setImageFromURL:[NSURL URLWithString:@"https://i.pinimg.com/736x/5b/c6/c5/5bc6c5387ff6f104fd642f2b375efba3.jpg"] processorKey:@"rounded" processor:^UIImage *(PINRemoteImageManagerResult *result, NSUInteger *cost)
 {
     CGSize targetSize = CGSizeMake(200, 300);
     CGRect imageRect = CGRectMake(0, 0, targetSize.width, targetSize.height);
     UIGraphicsBeginImageContext(imageRect.size);
     UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:imageRect cornerRadius:7.0];
     [bezierPath addClip];

     CGFloat sizeMultiplier = MAX(targetSize.width / result.image.size.width, targetSize.height / result.image.size.height);

     CGRect drawRect = CGRectMake(0, 0, result.image.size.width * sizeMultiplier, result.image.size.height * sizeMultiplier);
     if (CGRectGetMaxX(drawRect) > CGRectGetMaxX(imageRect)) {
         drawRect.origin.x -= (CGRectGetMaxX(drawRect) - CGRectGetMaxX(imageRect)) / 2.0;
     }
     if (CGRectGetMaxY(drawRect) > CGRectGetMaxY(imageRect)) {
         drawRect.origin.y -= (CGRectGetMaxY(drawRect) - CGRectGetMaxY(imageRect)) / 2.0;
     }

     [result.image drawInRect:drawRect];

     UIImage *processedImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return processedImage;
 }];

Swift

let imageView = FLAnimatedImageView()
imageView.pin_setImage(from: URL(string: "https://i.pinimg.com/736x/5b/c6/c5/5bc6c5387ff6f104fd642f2b375efba3.jpg")!, processorKey: "rounded")  { (result, unsafePointer) -> UIImage? in

    guard let image = result.image else { return nil }

    let radius : CGFloat = 7.0
    let targetSize = CGSize(width: 200, height: 300)
    let imageRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)

    UIGraphicsBeginImageContext(imageRect.size)

    let bezierPath = UIBezierPath(roundedRect: imageRect, cornerRadius: radius)
    bezierPath.addClip()

    let widthMultiplier : CGFloat = targetSize.width / image.size.width
    let heightMultiplier : CGFloat = targetSize.height / image.size.height
    let sizeMultiplier = max(widthMultiplier, heightMultiplier)

    var drawRect = CGRect(x: 0, y: 0, width: image.size.width * sizeMultiplier, height: image.size.height * sizeMultiplier)
    if (drawRect.maxX > imageRect.maxX) {
        drawRect.origin.x -= (drawRect.maxX - imageRect.maxX) / 2
    }
    if (drawRect.maxY > imageRect.maxY) {
        drawRect.origin.y -= (drawRect.maxY - imageRect.maxY) / 2
    }

    image.draw(in: drawRect)

    UIColor.red.setStroke()
    bezierPath.lineWidth = 5.0
    bezierPath.stroke()

    let ctx = UIGraphicsGetCurrentContext()
    ctx?.setBlendMode(CGBlendMode.overlay)
    ctx?.setAlpha(0.5)

    let logo = UIImage(named: "white-pinterest-logo")
    ctx?.scaleBy(x: 1.0, y: -1.0)
    ctx?.translateBy(x: 0.0, y: -drawRect.size.height)

    if let coreGraphicsImage = logo?.cgImage {
        ctx?.draw(coreGraphicsImage, in: CGRect(x: 90, y: 10, width: logo!.size.width, height: logo!.size.height))
    }

    let processedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return processedImage

}

Handle Authentication

Objective-C

[[PINRemoteImageManager sharedImageManager] setAuthenticationChallenge:^(NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, PINRemoteImageManagerAuthenticationChallengeCompletionHandler aCompletion) {
aCompletion(NSURLSessionAuthChallengePerformDefaultHandling, nil)];

Swift

PINRemoteImageManager.shared().setAuthenticationChallenge { (task, challenge, completion) in
  completion?(.performDefaultHandling, nil)
}

Support for high resolution images

Currently there are two ways PINRemoteImage is supporting high resolution images:

  1. If the URL contains an _2x. or an _3x. postfix it will be automatically handled by PINRemoteImage and the resulting image will be returned at the right scale.
  2. If it's not possible to provide an URL with an _2x. or _3x. postfix, you can also handle it with a completion handler:
NSURL *url = ...;
__weak UIImageView *weakImageView = self.imageView;
[self.imageView pin_setImageFromURL:url completion:^(PINRemoteImageManagerResult * _Nonnull result) {
  CGFloat scale = UIScreen.mainScreen.scale;
  if (scale > 1.0) {
    UIImage *image = result.image;
    weakImageView.image = [UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
    }
}];

Set some limits

// cache is an instance of PINCache as long as you haven't overridden defaultImageCache
PINCache *cache = (PINCache *)[[PINRemoteImageManager sharedImageManager] cache];
// Max memory cost is based on number of pixels, we estimate the size of one hundred 600x600 images as our max memory image cache.
[[cache memoryCache] setCostLimit:600 * [[UIScreen mainScreen] scale] * 600 * [[UIScreen mainScreen] scale] * 100];

// ~50 MB
[[cache diskCache] setByteLimit:50 * 1024 * 1024];
// 30 days
[[cache diskCache] setAgeLimit:60 * 60 * 24 * 30];

Installation

CocoaPods

Add PINRemoteImage to your Podfile and run pod install.

If you'd like to use WebP images, add PINRemoteImage/WebP to your Podfile and run pod install.

Carthage

Add github "pinterest/PINRemoteImage" to your Cartfile . See Carthage's readme for more information on integrating Carthage-built frameworks into your project.

Manually

Download the latest tag and drag the Pod/Classes folder into your Xcode project. You must also manually link against PINCache.

Install the docs by double clicking the .docset file under docs/, or view them online at cocoadocs.org

Git Submodule

You can set up PINRemoteImage as a submodule of your repo instead of cloning and copying all the files into your repo. Add the submodule using the commands below and then follow the manual instructions above.

git submodule add https://github.com/pinterest/PINRemoteImage.git
git submodule update --init

Requirements

PINRemoteImage requires iOS 7.0 or greater.

Contact

Garrett Moon @garrettmoon Pinterest

License

Copyright 2015 Pinterest, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

ktlint

An anti-bikeshedding Kotlin linter with built-in formatter
Kotlin
6,006
star
2

gestalt

A set of React UI components that supports Pinterest’s design language
JavaScript
4,205
star
3

PINCache

Fast, non-deadlocking parallel object cache for iOS, tvOS and OS X
Objective-C
2,644
star
4

secor

Secor is a service implementing Kafka log persistence
Java
1,832
star
5

teletraan

Teletraan is Pinterest's deploy system.
Java
1,792
star
6

querybook

Querybook is a Big Data Querying UI, combining collocated table metadata and a simple notebook interface.
TypeScript
1,728
star
7

knox

Knox is a secret management service
Go
1,216
star
8

pinball

Pinball is a scalable workflow manager
JavaScript
1,047
star
9

mysql_utils

Pinterest MySQL Management Tools
Python
878
star
10

elixometer

A light Elixir wrapper around exometer.
Elixir
827
star
11

snappass

Share passwords securely
Python
812
star
12

pymemcache

A comprehensive, fast, pure-Python memcached client.
Python
740
star
13

bonsai

Understand the tree of dependencies inside your webpack bundles, and trim away the excess.
JavaScript
739
star
14

esprint

Fast eslint runner
JavaScript
657
star
15

bender

An easy-to-use library for creating load testing applications
Go
654
star
16

rocksplicator

RocksDB Replication
C++
640
star
17

DoctorK

DoctorK is a service for Kafka cluster auto healing and workload balancing
Java
633
star
18

plank

A tool for generating immutable model objects
Swift
469
star
19

riffed

Provides idiomatic Elixir bindings for Apache Thrift
Elixir
307
star
20

thrift-tools

thrift-tools is a library and a set of tools to introspect Apache Thrift traffic.
Python
229
star
21

elixir-thrift

A Pure Elixir Thrift Implementation
Elixir
212
star
22

widgets

JavaScript widgets, including the Pin It button.
JavaScript
195
star
23

terrapin

Serving system for batch generated data sets
Java
176
star
24

singer

A high-performance, reliable and extensible logging agent for uploading data to Kafka, Pulsar, etc.
Java
173
star
25

git-stacktrace

Easily figure out which git commit caused a given stacktrace
Python
157
star
26

jbender

An easy-to-use library for creating load testing applications.
Java
155
star
27

ptracer

A library for ptrace-based tracing of Python programs
Python
154
star
28

react-pinterest

JavaScript
153
star
29

pinlater

PinLater is a Thrift service to manage scheduling and execution of asynchronous jobs.
Java
135
star
30

it-cpe-cookbooks

A suite of Chef cookbooks that we use to manage our fleet of client devices
Ruby
117
star
31

memq

MemQ is an efficient, scalable cloud native PubSub system
Java
111
star
32

psc

PubSubClient (PSC)
Java
110
star
33

pinterest-api-demo

JavaScript
105
star
34

PINOperation

Objective-C
102
star
35

api-quickstart

Code that makes it easy to get started with the Pinterest API.
Python
100
star
36

soundwave

A searchable EC2 Inventory store
Java
97
star
37

orion

Management and automation platform for Stateful Distributed Systems
Java
94
star
38

PINFuture

An Objective-C future implementation that aims to provide maximal type safety
Objective-C
81
star
39

kingpin

KingPin is the toolset used at Pinterest for service discovery and application configuration.
Python
69
star
40

arcanist-linters

A collection of custom Arcanist linters
PHP
61
star
41

pagerduty-monit

Wrapper scripts to integrate monit and PagerDuty.
Shell
60
star
42

pinrepo

Pinrepo is a highly scalable solution for storing and serving build artifacts such as debian packages, maven jars and pypi packages.
Python
57
star
43

quasar-thrift

A Thrift server that uses Quasar's lightweight threads to handle connections.
Java
47
star
44

yuvi

Yuvi is an in-memory storage engine for recent time series metrics data.
Java
45
star
45

transformer_user_action

Transformer-based Realtime User Action Model for Recommendation at Pinterest
Python
44
star
46

pinterest-python-sdk

An SDK that makes it quick and easy to build applications with Pinterest API.
Python
35
star
47

slackminion

A python bot framework for slack
Python
22
star
48

atg-research

Python
20
star
49

l10nmessages

L10nMessages is a library that makes internationalization (i18n) and localization (l10n) of Java applications easy and safe.
Java
17
star
50

arcanist-owners

An Arcanist extension for displaying file ownership information
PHP
16
star
51

api-description

OpenAPI descriptions for Pinterest's REST API
15
star
52

thriftcheck

A linter for Thrift IDL files
Go
13
star
53

.github

Pinterest's Open Source Project Template
11
star
54

pinterest-python-generated-api-client

This is the auto-generated code using OpenAPI generator. Generated code comprises HTTP requests to various v5 API endpoints.
Python
10
star
55

homebrew-tap

macOS Homebrew formulas to install Pinterest open source software
Ruby
9
star
56

wheeljack

Work with interdependent python repositories seemlessly.
Python
8
star
57

vscode-gestalt

Visual Studio Code extension for Gestalt, Pinterest's design system
TypeScript
7
star
58

ffffound

FFFFOUND Import tool for Pinterest
HTML
6
star
59

vscode-package-watcher

Watch package lock files and suggest to re-run npm or yarn.
TypeScript
5
star
60

graphql-lint-rules

Pinterest GraphQL Lint Rules
TypeScript
5
star
61

ss-gtm-template

This is a repository to implement the Google Tag Manager server-side tag template for Pinterest API for Conversions to be deployed into Google Community Template Gallery.
Smarty
4
star
62

pinterest-magento2-extension

PHP
3
star
63

Pinterest-Salesforce-Commerce-Cartridge

JavaScript
2
star
64

slate

Resource Lifecycle Management framework
Java
1
star