Convert the image to hexadecimal to send the image to e-paper

Overview

ConvertImageToHex

Convert the image to hexadecimal to send the image to e-paper

Conversion Order

// 0. hex로 변환할 이미지
var image = UIImage(named: "sample")
// 1. 이미지를 원하는 사이즈로 변경한다.
// sample size = 250*128
let resizedImage = image?.imageResizing
// 2. 이미지 컬러를 흑백으로 변경한다.
let blackAndWhiteImage = resizedImage?.convertToBlackAndWhite
// 3. 변환한 이미지에서 binary를 추출한다.
let binary = extractBinary(from: blackAndWhiteImage)
// 4. binary string을 hex로 변환한다.
let hexString = convertToHexString(with: binary)
// 5. 변환된 hex를 데이터로 변경한다.
let hexData = hexString.hexaData
// 6. 데이터를 전송한다.

Extension

String+Ext

  1. string to hexaData
var hexaData: Data { .init(hexa) }
private var hexa: UnfoldSequence<UInt8, Index> {
    sequence(state: startIndex) { startIndex in
        guard startIndex < self.endIndex else { return nil }
        let endIndex = self.index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex
        defer { startIndex = endIndex }
        let binary = self[startIndex..<endIndex]
        return UInt8(binary, radix: 16)
    }
}
  1. subString
func substring(from: Int, to: Int) -> String {
    guard from < self.count,
          to <= self.count,
          to >= 0,
          (to - from) >= 0 else {
              return "out of range"
          }

    let startIndex = index(self.startIndex, offsetBy: from)
    let endIndex = index(self.startIndex, offsetBy: to + 1)
    return String(self[startIndex ..< endIndex])
}
  1. padding to left
func paddingToLeft(toLength: Int, withPad: String, startingAt: Int) -> String {
    guard count < toLength else { return self }
    return String(
        self.padding(toLength: toLength,
                     withPad: withPad,
                     startingAt: startingAt).reversed()
    )
}

UIImage

  1. image resizing
var imageResizing: UIImage? {
    let resizeWidth = 250 /// sample size
    let resizeHeight = 128 /// sample size
    /// Begin Image Context
    UIGraphicsBeginImageContext(CGSize(width: resizeWidth,
                                       height: resizeHeight))
    self.draw(in: CGRect(x: 0,
                         y: 0,
                         width: resizeWidth,
                         height: resizeHeight))
    let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
    /// End Image Context
    UIGraphicsEndImageContext()
    return resizedImage
}
  1. convert to black and white
var convertToBlackAndWhite: UIImage? {
    /// 1. UIImage -> CIImage로 변환
    guard let currentCIImage = CIImage(image: self) else { return nil }
    /// 2. grayScale 필터 적용
    guard let grayScaleFilter = CIFilter(name: "CIPhotoEffectNoir") else { return nil }
    grayScaleFilter.setValue(currentCIImage, forKey: "inputImage")
    guard let grayScaleCIImage = grayScaleFilter.outputImage else { return nil }
    /// 3. Contrast & Brightness 를 이용한 흑백 이미지 만들기
    let blackAndWhiteParams: [String: Any] = [
        kCIInputImageKey: grayScaleCIImage,
        kCIInputContrastKey: 50.0,
        kCIInputBrightnessKey: 0.0
    ]
    guard let blackAndWhiteFilter = CIFilter(name: "CIColorControls",
                                             parameters: blackAndWhiteParams) else { return nil }
    guard let blackAndWhiteCIImage = blackAndWhiteFilter.outputImage else { return nil }
    /// 4. 흑백 CIImage를 CGImage로 변환
    let context = CIContext()
    guard let cgImage = context.createCGImage(blackAndWhiteCIImage,
                                              from: blackAndWhiteCIImage.extent) else { return nil }
    /// 5. UIImage로 return
    return UIImage(cgImage: cgImage)
}

How to Convert

  1. extract Binary
func extractBinary(from image: UIImage?) -> String {
    /// binary를 array형식으로 추출한다. (픽셀 단위로 binary를 뽑아내서 저장하기 위해)
    var binaryArray = [String]()
    guard let cgImage = image?.cgImage else { return "" }
    guard let data = cgImage.dataProvider?.data else { return "" }
    guard let bytes = CFDataGetBytePtr(data) else { return "" }
    let bytesPerPixel = cgImage.bitsPerPixel / cgImage.bitsPerComponent
    /// 세로(위에서 아래)로 탐색하며 바이너리를 구한다.
    /// 가로로 탐색하려면 2개의 for문을 반대로 사용하면 된다.
    for x in 0..<cgImage.width {
        for y in 0..<cgImage.height {
            let offset = (y * cgImage.bytesPerRow) + (x * bytesPerPixel)
            if bytes[offset] == 0 {
                binaryArray.append("0") /// 검정색은 0으로 간주
            }
            else {
                binaryArray.append("1") /// 이외의 색은 1로 간주
            }
        }
    }
    /// binary를 array형식으로 추출한뒤 string으로 내보낸다.
    return binaryArray.joined()
}
  1. convert to hexString
16진수 let binaryToHex = String(Int(extractBinary, radix: 2)!, radix: 16) /// padding 추가: 0F 가 F로 표현되는 경우를 방지하기 위함 let hex = binaryToHex.paddingToLeft(toLength: 2, withPad: "0", startingAt: 0) hexArray.append(hex) } return hexArray.joined() } ">
func convertToHexString(with binary: String) -> String {
    var binary = binary
    var hexArray = [String]()
    /// binary 8개씩 가져오기
    /// 이미지 사이즈가 250*128 이기 때문에 전체 binary 개수는 32,000개
    /// 전체 binary를 8개씩 잘라 hex로 변환한다. 때문에 for문을 위한 범위는 0..<4000
    for _ in 0..<4000 {
        /// hex로 변환할 binary 추출
        let extractBinary = binary.substring(from: 0, to: 7)
        /// 추출한 binary 삭제
        let startIdx = binary.index(binary.startIndex, offsetBy: 8)
        let modifiedBinary = "\(binary[startIdx...])"
        binary = modifiedBinary
        /// hex 변환
        /// 2진수 -> 16진수
        let binaryToHex = String(Int(extractBinary, radix: 2)!, radix: 16)
        /// padding 추가:  0F 가 F로 표현되는 경우를 방지하기 위함
        let hex = binaryToHex.paddingToLeft(toLength: 2,
                                            withPad: "0",
                                            startingAt: 0)
        hexArray.append(hex)
    }
    return hexArray.joined()
}
You might also like...
A complete Mac App: drag an image file to the top section and the bottom section will show you the text of any QRCodes in the image.

QRDecode A complete Mac App: drag an image file to the top section and the bottom section will show you the text of any QRCodes in the image. QRDecode

Twitter Image Pipeline is a robust and performant image loading and caching framework for iOS clients

Twitter Image Pipeline (a.k.a. TIP) Background The Twitter Image Pipeline is a streamlined framework for fetching and storing images in an application

Image-cropper - Image cropper for iOS

Image-cropper Example To run the example project, clone the repo, and run pod in

An instagram-like image editor that can apply preset filters passed to it and customized editings to a binded image.
An instagram-like image editor that can apply preset filters passed to it and customized editings to a binded image.

CZImageEditor CZImageEditor is an instagram-like image editor with clean and intuitive UI. It is pure swift and can apply preset filters and customize

Agrume - 🍋 An iOS image viewer written in Swift with support for multiple images.
Agrume - 🍋 An iOS image viewer written in Swift with support for multiple images.

Agrume An iOS image viewer written in Swift with support for multiple images. Requirements Swift 5.0 iOS 9.0+ Xcode 10.2+ Installation Use Swift Packa

AlamofireImage is an image component library for Alamofire

AlamofireImage AlamofireImage is an image component library for Alamofire. Features Image Response Serializers UIImage Extensions for Inflation / Scal

Image slide-show viewer with multiple predefined transition styles, with ability to create new transitions with ease.
Image slide-show viewer with multiple predefined transition styles, with ability to create new transitions with ease.

ATGMediaBrowser ATGMediaBrowser is an image slide-show viewer that supports multiple predefined transition styles, and also allows the client to defin

FMPhotoPicker is a modern, simple and zero-dependency photo picker with an elegant and customizable image editor
FMPhotoPicker is a modern, simple and zero-dependency photo picker with an elegant and customizable image editor

FMPhotoPicker is a modern, simple and zero-dependency photo picker with an elegant and customizable image editor Quick demo Batch select/deselect Smoo

GPUImage 2 is a BSD-licensed Swift framework for GPU-accelerated video and image processing.
GPUImage 2 is a BSD-licensed Swift framework for GPU-accelerated video and image processing.

GPUImage 2 Brad Larson http://www.sunsetlakesoftware.com @bradlarson [email protected] Overview GPUImage 2 is the second generation of th

Owner
Hankyeol Park
iOS Developer : )
Hankyeol Park
Swiftly convert country codes and cultural terms to all 269 emoji flags without hassle

Swiftly convert country codes and cultural terms to all 269 emoji flags without hassle

Arnold Rozon 2 May 9, 2022
Convert HEIC images to JPEG format on the Mac

heic2jpeg Convert HEIC images to JPEG format on the Mac A basic tool to convert Apple's obnoxious HEIC format images (as the default photo format for

Fazal Majid 2 Mar 1, 2022
Convert UIImage to ASCII art

BKAsciiImage As seen on Cmd.fm iOS App https://itunes.apple.com/app/cmd.fm-radio-for-geeks-hackers/id935765356 Installation BKAsciiImage is available

Barış Koç 427 Dec 17, 2022
Style Art library process images using COREML with a set of pre trained machine learning models and convert them to Art style.

StyleArt Style Art is a library that process images using COREML with a set of pre trained machine learning models and convert them to Art style. Prev

iLeaf Solutions Pvt. Ltd. 222 Dec 17, 2022
A Swift package to convert a colour to a name using Wikipedia's colour list

ColorName Usage import ColorName SwiftUI let myColorName = getName(for: Color.red) print(myColorName) UIKit let myColorName = getName(for: UIColor.red

Jia Chen 3 Aug 9, 2022
📷 A composable image editor using Core Image and Metal.

Brightroom - Composable image editor - building your own UI Classic Image Editor PhotosCrop Face detection Masking component ?? v2.0.0-alpha now open!

Muukii 2.8k Jan 3, 2023
An image download extension of the image view written in Swift for iOS, tvOS and macOS.

Moa, an image downloader written in Swift for iOS, tvOS and macOS Moa is an image download library written in Swift. It allows to download and show an

Evgenii Neumerzhitckii 330 Sep 9, 2022
📷 A composable image editor using Core Image and Metal.

Brightroom - Composable image editor - building your own UI Classic Image Editor PhotosCrop Face detection Masking component ?? v2.0.0-alpha now open!

Muukii 2.8k Jan 2, 2023
AsyncImage before iOS 15. Lightweight, pure SwiftUI Image view, that displays an image downloaded from URL, with auxiliary views and local cache.

URLImage URLImage is a SwiftUI view that displays an image downloaded from provided URL. URLImage manages downloading remote image and caching it loca

Dmytro Anokhin 1k Jan 4, 2023
AYImageKit is a Swift Library for Async Image Downloading, Show Name's Initials and Can View image in Separate Screen.

AYImageKit AYImageKit is a Swift Library for Async Image Downloading. Features Async Image Downloading. Can Show Text Initials. Can have Custom Styles

Adnan Yousaf 11 Jan 10, 2022