Convert a GIF to PNG in Swift

While it’s been around since the late 1980s, the Graphic Interchange Format (GIF) has definitely upped its popularity over the past decade due to its wide support between online applications and its capacity for animations. However, the PNG format, which was developed in the mid-1990s as a replacement for GIF, offers a broader range of color and transparency options. If you need to convert a GIF to PNG, we can help you avoid the lengthy process of writing the necessary code by providing you with an API solution in Swift that will perform the function for you.

To use the image API in Swift, you simply need to input your target file into the following code:

import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
var semaphore = DispatchSemaphore (value: 0)let parameters = [
"key": "imageFile",
"src": "/path/to/file",
"type": "file"
]] as [[String : Any]]
let boundary = "Boundary-\(UUID().uuidString)"
var body = ""
var error: Error? = nil
for param in parameters {
if param["disabled"] == nil {
let paramName = param["key"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if param["contentType"] != nil {
body += "\r\nContent-Type: \(param["contentType"] as! String)"
let paramType = param["type"] as! String
if paramType == "text" {
let paramValue = param["value"] as! String
body += "\r\n\r\n\(paramValue)\r\n"
} else {
let paramSrc = param["src"] as! String
let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
let fileContent = String(data: fileData, encoding: .utf8)!
body += "; filename=\"\(paramSrc)\"\r\n"
+ "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
body += "--\(boundary)--\r\n";
let postData = .utf8)
var request = URLRequest(url: URL(string: "")!,timeoutInterval: Double.infinity)
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
print(String(data: data, encoding: .utf8)!)

With this quick operation, you’ll have your new PNG file available in no time at all.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store