ImageKitIO 3.0.0

ImageKitIO 3.0.0

ImageKit 开发者 维护。



  • ImageKit 开发者和 ahnv

ImageKit.io

ImageKit.io iOS SDK

Version Swift CI codecov License: MIT Twitter Follow

ImageKit iOS Pod 允许您在客户端使用实时 图像缩放优化文件上传

安装

要求

库需要 Swift 4.0 或以上版本。

CocoaPods

您可以通过将 ImageKit 添加到您的 Podfile 中使用 CocoaPods 进行安装。

use_frameworks!

target 'target_name' do
    pod 'ImageKitIO'
end

使用说明

初始化

您需要通过提供publicKeyurlEndpoint来初始化SDK。您可以在应用程序或启动活动(launcher activity)中完成此操作。需要在SDK中的任何其他功能之前调用此方法,否则将抛出异常。

authenticationEndpoint仅在您需要使用上传功能时才需要。

注意:不要在任何客户端代码(包括此SDK及其初始化)中包含您的私钥。

// AppDelegate.swift

ImageKit.init(
    publicKey: "your_public_api_key=", 
    urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", 
    transformationPosition: TransformationPosition.PATH, 
    authenticationEndpoint: "http://www.yourserver.com/auth")

快速示例

构造URL

使用图像路径

//https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-400.00,ar-3-2
ImageKit.shared.url(
            path: "default-image.jpg",
            transformationPosition: "query"
        )
        .height(height: 400)
        .aspectRatio(width: 3, height: 2)
        .create()

使用完整的图像URL

// https://ik.imagekit.io/your_imagekit_id/medium_cafe_B1iTdD0C.jpg?tr=oi-logo-white_SJwqB4Nfe.png,ox-10,oy-20
ImageKit.shared.url(
            src: "https://ik.imagekit.io/your_imagekit_id/medium_cafe_B1iTdD0C.jpg",
            transformationPosition: "path"
        )
        .overlayImage("logo-white_SJwqB4Nfe.png")
        .overlayX(10)
        .overlayY(20)
        .create()

使用自定义参数

// https://ik.imagekit.io/your_imagekit_id/plant.jpeg?tr=w-400,ot-Hand with a green plant,otc-264120,ots-30,ox-10,oy-10
ImageKit.shared.url(
    src : "https://ik.imagekit.io/your_imagekit_id/plant.jpeg?tr=oi-logo-white_SJwqB4Nfe.png,ox-10,oy-20"
    )
        .addCustomTransformation("w", "400")
        .overlayText("Hand with a green plant")
        .overlayTextColor("264120")
        .overlayTextSize(30)
        .overlayX(10)
        .overlayY(10)
        .create()

从 UIImage 上传文件

let image: UIImage
ImageKit.shared.uploader().upload(
  file: image,
  fileName: "sample-image.jpg",
  useUniqueFilename: true,
  tags: ["demo"],
  folder: "/",
  isPrivateFile: false,
  customCoordinates: "",
  responseFields: "",
  signatureHeaders: ["x-test-header":"Test"],
  progress: { progress in
  	// Handle Progress
  },
  completion: { result in 
  	 switch result{
            case .success(let uploadAPIResponse):
                // Handle Success Response
            case .failure(let error as UploadAPIError):
                // Handle Upload Error
            case .failure(let error):
                // Handle Other Errors
      }
  }
)

从远程 URL 上传文件

ImageKit.shared.uploader().upload(
  file: "https://www.example.com/sample-image.jpg",
  fileName: "sample-image.jpg",
  useUniqueFilename: true,
  tags: ["demo"],
  folder: "/",
  isPrivateFile: false,
  customCoordinates: "",
  responseFields: "",
  signatureHeaders: ["x-test-header":"Test"],
  progress: { progress in
  	// Handle Progress
  },
  completion: { result in 
  	 switch result{
            case .success(let uploadAPIResponse):
                // Handle Success Response
            case .failure(let error as UploadAPIError):
                // Handle Upload Error
            case .failure(let error):
                // Handle Other Errors
      }
  }
)

使用数据上传文件

let data : Data
ImageKit.shared.uploader().upload(
  file: data,
  fileName: "sample-image.jpg",
  useUniqueFilename: true,
  tags: ["demo"],
  folder: "/",
  isPrivateFile: false,
  customCoordinates: "",
  responseFields: "",
  signatureHeaders: ["x-test-header":"Test"],
  progress: { progress in
  	// Handle Progress
  },
  completion: { result in 
  	 switch result{
            case .success(let uploadAPIResponse):
                // Handle Success Response
            case .failure(let error as UploadAPIError):
                // Handle Upload Error
            case .failure(let error):
                // Handle Other Errors
      }
  }
)

演示应用程序

组件

该库包含3个主要类

  • ImageKit 用于定义应用程序使用的选项,如 urlEndpointpublicKeyauthenticationEndpoint
  • ImageKitURLConstructor 用于 构建图片 URL
  • ImageKitUploader用于客户端<ды href="#file-upload">文件上传。

ImageKit

为了使用SDK,您需要提供一些配置参数。

ImageKit.init(
  urlEndpoint: "https://ik.imagekit.io/your_imagekit_id", // Required.
  publicKey: "your_public_api_key=",  //Optional
  transformationPosition: TransformationPosition.PATH, //Optional
  authenticationEndpoint: "http://www.yourserver.com/auth" //Optional
)
  • urlEndpoint是使用SDK所必需的。您可以从ImageKit仪表板(https://imagekit.io/dashboard#url-endpoints)获取URL端点。
  • publicKeyauthenticationEndpoint参数是如果您想使用SDK进行客户端文件上传所必需的。您可以从ImageKit仪表板的开发者部分(https://imagekit.io/dashboard#developers)获取这些参数。
  • transformationPosition是可选的。此参数的默认值是TransformationPosition.PATH。可接受值是TransformationPosition.PATHTransformationPosition.QUERY

注意:不要将您的私钥包含在任何客户端代码中。

构建图像URL

ImageKitURLConstructor用于创建可实时渲染和操作图像的URL。通过链接函数执行转换。

ImageKitURLConstructor可以通过调用包含以下参数的ImageKit.shared.url(...)进行初始化:

参数 类型 描述
urlEndpoint String 可选。附加到图像路径之前的基准URL。如果没有指定,则使用父IKContext组件中指定的URL端点。例如,https://ik.imagekit.io/your_imagekit_id/endpoint/
path String 条件。这是图像存在的路径。例如,/path/to/image.jpg。需要指定pathsrc参数以生成URL。
src String 条件。这是已映射到ImageKit的图像的完整URL。例如,https://ik.imagekit.io/your_imagekit_id/endpoint/path/to/image.jpg。需要指定pathsrc参数以生成URL。
transformationPosition TransformationPosition 可选。默认值是`.PATH`,将转换字符串作为URL路径参数放置。它也可以指定为`.QUERY`,这将转换字符串添加为URL的查询参数,即tr。如果您使用src参数创建URL,那么转换字符串总是作为查询参数添加。

可以将要应用于URL的转换链接到ImageKit.shared.url(...)。请参阅<а href="#list-of-supported-transformations">不同转换的列表。可以通过调用函数chainTransformation添加<а href="https://docs.imagekit.io/features/image-transformations/chained-transformations" rel="nofollow">链式转换的步骤。

基础示例

// https://ik.imagekit.io/your_imagekit_id/default-image.jpg?tr=h-400.00,ar-3-2
ImageKit.shared.url(
  path: "default-image.jpg",
  transformationPosition: "query"
)
.height(height: 400)
.aspectRatio(width: 3, height: 2)
.create()

更多示例可以在 Tests/Tests.swift 找到

支持的转换列表

支持的转换及其在ImageKit中的使用列表,可以在此处找到:https://docs.imagekit.io/imagekit-docs/image-transformations。该SDK为每个转换参数提供了一个函数,使代码更加简单易读。如果ImageKit支持某个转换,但在此表下找不到其名称,则可以使用addCustomTransformation函数,并将ImageKit文档中的转换代码作为第一个参数,将值作为第二个参数传递。例如 - .addCustomTransformation("w", "400")

展开
支持的转换名称 转换函数原型 转换为参数
高度 height(height: Int) h
宽度 width(width: Int) w
长宽比 aspectRatio(width: Int, height: Int) ar
质量 quality(quality: Int) q
裁剪 crop(cropType: CropType) c
裁剪模式 cropMode(cropMode: CropMode) cm
x, y focus(x: Int, y: Int) x, y
focus focus(focusType: FocusType) fo
格式 format(format: Format) f
半径 radius(radius: Int) r
背景 background(backgroundColor: String)
background(backgroundColor: UIColor)
bg
边框 border(borderWidth: Int, borderColor: String)
border(borderWidth: Int, borderColor: UIColor)
b
旋转 rotation(rotation: Rotation) rt
模糊 blur(blur: Int) bl
名称 named(namedTransformation: String) n
覆盖X overlayX(overlayX: Int) ox
覆盖Y overlayY(overlayY: Int) oy
覆盖焦点 overlayFocus(overlayFocus: OverlayFocusType) ofo
覆盖高度 overlayHeight(overlayHeight: Int) oh
覆盖宽度 overlayWidth(overlayWidth: Int) ow
覆盖图片 overlayImage(overlayImage: String) oi
覆盖图片裁剪 overlayImageTrim(overlayImageTrim: Bool) oit
覆盖图片长宽比 overlayImageAspectRatio(width: Int, height: Int) oiar
覆盖图片背景 overlayImageBackground(overlayImageBackground: String)
overlayImageBackground(overlayImageBackground: UIColor)
oibg
覆盖图片边框 overlayImageBorder(borderWidth: Int, borderColor: String)
overlayImageBorder(borderWidth: Int, borderColor: UIColor)
oib
覆盖图片DPR overlayImageDPR(dpr: Float) oidpr
覆盖图片质量 overlayImageQuality(quality: Int) oiq
覆盖图片裁剪 overlayImageCropping(cropMode: CropMode) oic
覆盖文本 overlayText(overlayText: String) ot
覆盖文本字体大小 overlayTextFontSize(overlayTextSize: Int) ots
覆盖文本字体族 overlayTextFontFamily(overlayTextFontFamily: OverlayTextFont) otf
overlayTextColor overlayTextColor(overlayTextColor: String)
overlayTextColor(overlayTextColor: UIColor)
otc
overlayTextTransparency overlayTextTransparency(overlayTextTransparency: Int) oa
overlayAlpha overlayAlpha(overlayAlpha: Int) oa
overlayTextTypography overlayTextTypography(overlayTextTypography: OverlayTextTypography) ott
overlayBackground overlayBackground(overlayBackground: String)
overlayBackground(overlayBackground: UIColor)
obg
overlayTextEncoded overlayTextEncoded(overlayTextEncoded: String, encoded: Bool = false) ote
overlayTextWidth overlayTextWidth(width: Int) otw
overlayTextBackground overlayTextBackground(overlayTextColor: String)
overlayTextBackground(overlayTextColor: UIColor)
otbg
overlayTextPadding overlayTextPadding(overlayTextPadding: String)
overlayTextPadding(overlayTextPadding: Int)
overlayTextPadding(verticalPadding: Int, horizontalPadding: Int)
overlayTextPadding(topPadding: Int, horizontalPadding: Int, bottomPadding: Int)
overlayTextPadding(topPadding: Int, rightPadding: Int, bottomPadding: Int, leftPadding: Int)
otp
overlayTextInnerAlignment overlayTextInnerAlignment(overlayTextInnerAlignment: OverlayTextInnerAlignment) otia
overlayRadius overlayRadius(radius: Int) or
progressive progressive(flag: Bool) pr
lossless lossless(flag: Bool) lo
trim trim(flag: Bool)
trim(value: Int)
t
metadata metadata(flag: Bool) md
colorProfile colorProfile(flag: Bool) cp
defaultImage defaultImage(defaultImage: String) di
dpr dpr(dpr: Float) dpr
effectSharpen effectSharpen(value: Int = 0) e-sharpen
effectUSM effectUSM(radius: Float, sigma: Float, amount: Float, threshold: Float) e-usm
effectContrast effectContrast(flag: Bool) e-contrast
effectGray effectGray(flag: Bool) e-grayscale
original original() orig

文件上传

SDK通过使用ImageKit.shared.uploader().upload(...)方法提供简单接口,将文件上传到ImageKit媒体库。它接受ImageKit上传API所支持的所有参数。

请确保在SDK初始化期间已指定authenticationEndpoint。SDK会向该端点发送HTTP GET请求,并期望返回一个包含三个字段(即signaturetokenexpire)的JSON响应。

了解如何在服务器上实现authenticationEndpoint

ImageKit.shared.uploader().upload(...)接受以下参数:

参数 类型 描述
file 数据 / UIImage / 字符串 必需。
fileName String 必需。如未指定,则选择文件系统名称。
useUniqueFileName 布尔值 可选。接受truefalse。默认值为true。指定是否为此文件使用唯一文件名。
tags 字符串数组 可选。在上传文件时设置标签,例如["tag1","tag2"]
folder String 可选。要上传文件的文件夹路径(例如/images/folder/)。如果该文件夹不存在,则会创建一个新文件夹。
isPrivateFile 布尔值 可选。接受 truefalse。默认值是 false。指定是否将文件标记为私有。仅与图像类型文件相关。
customCoordinates String 可选。在图像中定义一个重要的区域。仅与图像类型文件相关。作为字符串传递,包含左上角的 xy 坐标,以及感兴趣区域大小的 widthheight,格式为 x,y,width,height。例如 - 10,10,100,100
responseFields 字符串数组 可选。你希望上传 API 在响应中返回的字段值。例如,将此字段的值设置为 ["tags", "customCoordinates", "isPrivateFile"],以获取响应中 tagscustomCoordinatesisPrivateFile 的值。
progress ((进度) -> Void) 可选。
completion (Result<(HTTPURLResponse?, UploadAPIResponse?), Error>) -> Void 必需。

示例用法

ImageKit.shared.uploader().upload(
  file: image,
  fileName: "sample-image.jpg",
  useUniqueFilename: true,
  tags: ["demo"],
  folder: "/",
  isPrivateFile: false,
  customCoordinates: "",
  responseFields: "",
  signatureHeaders: ["x-test-header":"Test"],
  progress: { progress in
  	// Handle Progress
  },
  completion: { result in 
  	 switch result{
            case .success(let uploadAPIResponse):
                // Handle Success Response
            case .failure(let error as UploadAPIError):
                // Handle Upload Error
            case .failure(let error):
                // Handle Other Errors
      }
  }
)

支持

有关反馈或报告任何问题或常规实施支持,请通过 [email protected] 联系我们。

链接

许可协议

允许在 MIT 许可协议下发布。