简体   繁体   English

快速将双数组转换为 UIImage

[英]Convert a Double Array to UIImage in swift

Is it possible to convert a double array to UIImage using UIImage function?是否可以使用 UIImage 函数将双数组转换为 UIImage?

var ImageDouble = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]

UIImage function asks for String. UIImage 函数需要字符串。 I tried converting the array on individual element to strings and the whole thing to string, I get a nill result.我尝试将单个元素上的数组转换为字符串,并将整个内容转换为字符串,但结果为 nill。 Can someone help?有人可以帮忙吗?

[Edit:] [编辑:]

As it seems I was not really clear on my problem.看来我并不清楚我的问题。 To make it more clear, I am developing a software which crops numbers & operators from a mathematical expression and shows me all the chunks one by one.为了更清楚,我正在开发一个软件,它可以从数学表达式中裁剪数字和运算符,并逐个向我显示所有块。 Now, how do I go about it in Swift?现在,我该如何在 Swift 中进行呢? :

Step-1: I have a grayscale image provided.第 1 步:我提供了一个灰度图像。 I read it using UIImage function.我使用 UIImage 函数阅读它。 I convert it to a custom RGBA function as follows so that I can deal on a pixel level like we do in MATLAB or Python or C++.我将其转换为自定义 RGBA 函数,如下所示,以便我可以像在 MATLAB、Python 或 C++ 中那样处理像素级别。 The function is inspired from many websites's suggestions to use it.该功能的灵感来自许多网站的使用建议。

struct Pixel {
var value: UInt32
var red: UInt8 {
    get { return UInt8(value & 0xFF) }
    set { value = UInt32(newValue) | (value & 0xFFFFFF00) }
}
var green: UInt8 {
    get { return UInt8((value >> 8) & 0xFF) }
    set { value = (UInt32(newValue) << 8) | (value & 0xFFFF00FF) }
}
var blue: UInt8 {
    get { return UInt8((value >> 16) & 0xFF) }
    set { value = (UInt32(newValue) << 16) | (value & 0xFF00FFFF) }
}
var alpha: UInt8 {
    get { return UInt8((value >> 24) & 0xFF) }
    set { value = (UInt32(newValue) << 24) | (value & 0x00FFFFFF) }
}

} }

struct RGBA {
var pixels: UnsafeMutableBufferPointer<Pixel>
var width: Int
var height: Int
init?(image: UIImage) {
    guard let cgImage = image.CGImage else { return nil }
    width = Int(image.size.width)
    height = Int(image.size.height)
    let bitsPerComponent = 8
    let bytesPerPixel = 4
    let bytesPerRow = width * bytesPerPixel
    let imageData = UnsafeMutablePointer<Pixel>.alloc(width * height)
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    var bitmapInfo: UInt32 = CGBitmapInfo.ByteOrder32Big.rawValue
    bitmapInfo |= CGImageAlphaInfo.PremultipliedLast.rawValue & CGBitmapInfo.AlphaInfoMask.rawValue
    guard let imageContext = CGBitmapContextCreate(imageData, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo) else { return nil }
    CGContextDrawImage(imageContext, CGRect(origin: CGPointZero, size: image.size), cgImage)
    pixels = UnsafeMutableBufferPointer<Pixel>(start: imageData, count: width * height)
}

func toUIImage() -> UIImage? {
    let bitsPerComponent = 8
    let bytesPerPixel = 4
    let bytesPerRow = width * bytesPerPixel
    let colorSpace = CGColorSpaceCreateDeviceRGB()
    var bitmapInfo: UInt32 = CGBitmapInfo.ByteOrder32Big.rawValue
    bitmapInfo |= CGImageAlphaInfo.PremultipliedLast.rawValue & CGBitmapInfo.AlphaInfoMask.rawValue
    let imageContext = CGBitmapContextCreateWithData(pixels.baseAddress, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo, nil, nil)
    guard let cgImage = CGBitmapContextCreateImage(imageContext) else {return nil}
    let image = UIImage(CGImage: cgImage)
    return image
}

} }

Step-2: Now I take one channel of the image [Red: it does not matter which one I take, since all the channels have same output] and apply my custom median filter of kernel size 5x5.第 2 步:现在我取图像的一个通道 [红色:我取哪个通道并不重要,因为所有通道都有相同的输出] 并应用我的内核大小为 5x5 的自定义中值滤波器。

Step-3: Next, I do the binarization of the image using Nibblack approximation,where I used averaging filter and standard deviation.第 3 步:接下来,我使用 Nibblack 近似对图像进行二值化,其中我使用了平均滤波器和标准偏差。

Step-4: After that, I used connected component labelling to separate out different connected components of the image. Step-4:之后,我使用连接组件标记来分离图像的不同连接组件。

Step-5: Finally, I need to crop the labelled images and resize it.第 5 步:最后,我需要裁剪标记的图像并调整其大小。 For cropping from the original image , I know the location by using a smart location algorithm.为了从原始图像中裁剪,我通过使用智能位置算法知道位置。 For resizing, I want to use Core Graphics Resizing filter.对于调整大小,我想使用 Core Graphics Resizing 过滤器。 However, for that I need to convert my current output [a two-dimensional array or flattened] to UIImage or CGImage.但是,为此我需要将当前输出 [二维数组或扁平化] 转换为 UIImage 或 CGImage。

That's my real question: How do I convert to UIImage or CGImage from two-dimensional array or flattened array which are of type Array<Double> or Array<Int> ?那是我真正的问题:如何从二维数组或扁平数组( Array<Double>Array<Int>类型)转换为 UIImage 或 CGImage ?

Try this:尝试这个:

var ImageDouble = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]
let images = ImageDouble.map{ UIImage(named: "\($0)")}

the map function will transform your array to another array. map 函数会将您的数组转换为另一个数组。

Just try this:试试这个:

var str:[String] = [];

for (var i=0;i<ImageDouble.count;i++){
   str.append(String(ImageDouble[i]));
}
print(str)

But why would you pass a String of numbers to an UIImage?但是为什么要将一串数字传递给 UIImage 呢? Are images in your asset named as numbers?资产中的图像是否以数字命名?

Looks like you want to render 1, 2, etc into a bitmap.看起来您想将 1、2 等渲染为位图。

First you need a function to do that, and then use flatMap on the array of doubles using this.首先,您需要一个函数来执行此操作,然后使用 this 在双精度数组上使用 flatMap。 This will ensure you get an array of UIImages in a safe way by filtering if any nil results when we try to create images.当我们尝试创建图像时,这将通过过滤是否有任何 nil 结果来确保您以安全的方式获得 UIImages 数组。

func createNumberImage(number:Double) -> UIImage?{

    //Set a frame that you want.
    let frame = CGRect(x: 0, y: 0, width: 200, height: 200)
    let view = UIView(frame:frame )
    view.backgroundColor = UIColor.redColor()

    let label = UILabel(frame:frame)
    view.addSubview(label)

    label.font  = UIFont.systemFontOfSize(100);
    label.text = String(format: "%.1lf", arguments:[number])
    label.textAlignment = NSTextAlignment.Center
    view

    UIGraphicsBeginImageContext(view.bounds.size);
    view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return screenShot
}

let doubles = [1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0]

//Get the array of UIImage objects.  
let images = doubles.flatMap { createNumberImage($0) }

You can use playground to verify this working.您可以使用 Playground 来验证此工作。 Also you might want to set proper background and text colors and font size to suite your requirements.此外,您可能希望设置适当的背景和文本颜色以及字体大小以满足您的要求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM