I have converted my images with this codes below and this will return base64 of my images but the problem is that when I upload them into the server I just see the white image - can you suggest me the better way to convert images to base64 or this is the best way that I choose
here is the converting image to base64
func base64(from image: UIImage) -> String? {
UIGraphicsBeginImageContext(image.size)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(image!, 1.0)
if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) {
return imageString
}
return nil
}
Try this method:
func convertImageToBase64(_ image:UIImage) -> String
{
let imageData = UIImageJPEGRepresentation(image, 1)//get imageData from image
if(imageData != nil)
{
let Strbase64 = imageData?.base64EncodedString(options: .endLineWithCarriageReturn)//encode imageData
return Strbase64!//return encoded string
}
return ""
}
You passed a UIImage to this method, but never did anything with it, but rather created a new UIImage using UIGraphicsGetImageFromCurrentImageContext, but you never drew anything to that context. That's why the resulting images are white.
But you don't need those UIGraphics calls at all. Just grab the JPEG representation of the UIImage that you passed into this method, and convert it to a base 64 encoded string:
func convertImageToBase64(_ image: UIImage) -> String? {
return UIImageJPEGRepresentation(image, 1)?.base64EncodedString()
}
It is white because nothing is drawn on current context !!!
You are just UIGraphicsBeginImageContext with size
and get with UIGraphicsGetImageFromCurrentImageContext
it will always gives you a white image and there is no relation with Base64
If you want to render something then use like below
yourImageView.layer.render(in: UIGraphicsGetCurrentContext()!)
and after that fetch image from currentContext
EDIT
func base64(from image: UIImage) -> String? {
UIGraphicsBeginImageContext(image.size)
image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let imageData = UIImageJPEGRepresentation(image!, 1.0)
if let imageString = imageData?.base64EncodedString(options: .endLineWithLineFeed) {
return imageString
}
return nil
}
First check wether the error you are facing is from your app or server side .You can choose online base64 to image converter .Copy your base64 String and check them first , you can choose this link
https://codebeautify.org/base64-to-image-converter
Related
I am masking an image using an image_mask, the following code shows that:
func maskOriginalImage() -> UIImage? {
if(self.maskImage != nil && self.originalImage != nil){
let maskReference = self.maskImage?.cgImage!
let maskedReference = self.originalImage?.cgImage!.masking(maskReference!)
self.maskImage = nil
return UIImage(cgImage: maskedReference!)
}
return nil
Now I want to save the masked image to photo library.
func saveImageToLibrary(){
UIImageWriteToSavedPhotosAlbum(self.segmentedimage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
But while saving the maskedImage, original image is saved. The workaround I found is to create a new UIimagecontext and draw the maskedimage in the context and use that image to save.
func getImageFromContext() -> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.size, false, scale)
draw(in: CGRect(origin: .zero, size: size))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
Why I just can't save the masked image directly? I am relatively new to IOS development so any inputs will be helpful.
I'm trying to retrieve and visualize an image from postgres to iOS, and I tried turning into Data and then UIImage but with no luck, when i create the UIImage it returns nil.
As you can see from the image below, I get that string from the db, with double backslash and x, that should be normal, I tried both to keep the escaping symbols and to trim them, I also tried to initialize the Data with both initializer with byte: and base64Encoded, with and without options but the image is always nil.
screenshot from xcode
func dataToImage(data:String)->Image{
var imageData = Data(bytes: "68747470733a2f2f73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f696c6172696f73616c6174696e6f2f31423236303332462d363935422d344342432d393733412d3342413936343841334535372d373136312d303030303145323833464643303541442e6a706567", count: data.count)
var base64data = Data(base64Encoded: "68747470733a2f2f73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f696c6172696f73616c6174696e6f2f31423236303332462d363935422d344342432d393733412d3342413936343841334535372d373136312d303030303145323833464643303541442e6a706567", options: .ignoreUnknownCharacters)
return Image(uiImage: UIImage(data: imageData)!)
}
the string I get from the db:
data String "\\x68747470733a2f2f73332e65752d63656e7472616c2d312e616d617a6f6e6177732e636f6d2f696c6172696f73616c6174696e6f2f31423236303332462d363935422d344342432d393733412d3342413936343841334535372d373136312d303030303145323833464643303541442e6a706567"
Any help appreciated, thanks!
You are not saving image data correctly =/
To get UIImage Data properly you should:
let data = yourImage.jpegData(compressionQuality: 1)
It will return an Data
So, save it like a String and its ready!
To set image from Data its like these:
let data = Data(base64Encoded: myString)
let newImage = UIImage(data: data)
To debug more easily use this string to convert to Data and Image. This string provides us a Data and an Image properly
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCABAAEADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD3+iiopp1gALg4PcUJXAloqut7A/Rqk+0Rf38fUYp2YrklFRfaIi2A2foM0vnR5wXAPoeKLMdySikDK3RgfoaWkAVma0+y1B9606x/EJIskx13VUdxPYp2zl1GVyParjvkx43KWUAnjPU+tZdr9zkVad9ph7jaOD9TWjJMnTNS+26C15qFqLuWCeZNkEIZmKsF+Vc9cGtJdetreFUOm6pFGP8ApxchRn2z61z+kmKOwmD25lA1S8C44x84rpYZBPHH5R8lyf4o2fPt1GKTVwFk1jTBLLE9ysTxOY2M0bRru54DMAG6djWxZ824+p/nWJHeyeV5cqyZxyy4x+RY1s6ec2i5OTk8n60pbDW5arE8SNi1jA/vf4Vt15/8TfFcPhlNOWW0kuftRfAjmEZXbg55Bz1pU4uUrLcJSUVeWxp2eMYLLj2rQKwtGjPjgAZ3ds14sPi3aRNkaHcH63i//E1KPjVAoH/EknGP+nxP/iK39hU7fkZqtTfU9A8P+W+m3LhA6nUrtlB/3x61src7GVvs06KByFjU5/EGvMvD3jS4/sTTYbTSDc3F891c4a8SMIPO28krz0qw3izWJHQroSfOQqn+04iOTjqU4qOR/wBNF8y/pM9GW4jIKrbThevEWB/OtrSz/omB2YivH4/GmqRoZ/7GhKDg/wDE1hHP/fI/WvRfAWvjxFoEt59m+zMly8LxecsuCoH8S8d6mUXa/wCqGpK9jdl02GYcy3S/7lzIv8mrJvvBOh6p5f8AaVu995efL+1yGUpnGcFs46CuhorNSa2HZHI/8Kx8H/8AQDtP+/K/4Up+GXg8qQdDtMEY4iUfyFdbRT55dwsjlE+G3hJLaG2/saCSGAMIll+fYGYsQC2SOSTTh8N/Bw/5l6wP1hFdTRRzS7hZHNL8PfCC/wDMu6cfrAprY03SNP0aBoNNs4rWFm3GOJdq59cdKu0UnJvdhZH/2Q=="
I hope it helped you!
Cheers
try this
class ImageConverter {
func base64ToImage(_ base64String: String) -> UIImage? {
guard let imageData = Data(base64Encoded: base64String) else { return nil }
return UIImage(data: imageData)
}
func imageToBase64(_ image: UIImage) -> String? {
return image.jpegData(compressionQuality: 1)?.base64EncodedString()
}
}
I have a question about UIImage convert to base64 String.
And I already resize my image width and height (1024 x 768).
Then I convert this image to base64 String.
But when I use this base64 String to UIImage and look image width and height not I resize before(2304.0 x 3072.0).
How to make my base64 String image size correctly?
guard let image = image else { return }
print("image => \(image)")
//image => <UIImage:0x283cce7f0 anonymous {768, 1024}>
guard let base64ImageString = image.toBase64(format: .jpeg(0.2)) else { return }
let dataDecoded : Data = Data(base64Encoded: base64ImageString, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
let height = decodedimage?.size.height
let width = decodedimage?.size.width
print("====) \(String(describing: width)) / \(String(describing: height))")
//====) Optional(2304.0) / Optional(3072.0)
public enum ImageFormat {
case png
case jpeg(CGFloat)
}
extension UIImage {
public func toBase64(format: ImageFormat) -> String? {
var imageData: Data?
switch format {
case .png:
imageData = self.pngData()
case .jpeg(let compression):
imageData = self.jpegData(compressionQuality: compression)
}
return imageData?.base64EncodedString()
}
}
Try this way, the below code resizes your image, and should be added before you change it to base64.
guard let image = image else { return }
print("image => \(image)")
//image => <UIImage:0x283cce7f0 anonymous {768, 1024}>
let desiredSize = CGSize(width: 768, height: 1024)
UIGraphicsBeginImageContextWithOptions(desiredSize, false, 1.0)
image.draw(in: CGRect(origin: CGPoint.zero, size: CGSize(width:
desiredSize.width, height: desiredSize.height)))
let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let base64ImageString = resizedImage.toBase64(format: .jpeg(0.2)) else { return }
I need to convert the image to/from Base64.
All working fine for JPG files, but if I upload PNG and then open it in the app it leads to the crash with error
"Unexpectedly found nil while unwrapping an Optional value"
while trying to create Data from the encoded string
Here is my code:
For Encoding:
static func base64Convert(base64String: String?) -> UIImage {
var decodedImage = #imageLiteral(resourceName: "no_prof_image")
if ((base64String?.isEmpty)! || (base64String?.contains("null"))!) {
return decodedImage
}else {
if let imageBase64String = base64String,
let dataDecoded = Data(base64Encoded: imageBase64String, options: .ignoreUnknownCharacters) {
decodedImage = UIImage(data: dataDecoded) ?? #imageLiteral(resourceName: "no_prof_image")
}
return decodedImage
}
}
For Decoding:
static func makeProfileBase64FromImage(image: UIImage) -> String? {
var imageData : Data?
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
imageData = jpegData
} else if let pngData = UIImagePNGRepresentation(image) {
imageData = pngData
}
return imageData?.base64EncodedString()
}
What I tried:
1) All encoding options
2) All decoding options
3) Swap UIImageJPEGRepresentation to UIImagePNGRepresentation. It leads to the same error but with jpg images.
UPDATE
Here is code how I send data to the server:
var imageToSend : String = "null"
if profileImage.image != #imageLiteral(resourceName: "no_prof_image"),
let validImage = profileImage.image,
let imageBase64 = AppUtils.makeProfileBase64FromImage(image: validImage) {
imageToSend = imageBase64
}
let parameters : Parameters = [
"image": imageToSend
]
Alamofire.request(AppUtils.API_URL + "update_profile.php", method: .post, parameters: parameters)
.validate().responseData() {response in
switch response.result {
case .success:
//...Some stuff
break
case .failure:
//...Some stuff
break
}
}
Part of the string that came to the server:
/9j/4AAQSkZJRgABAQAASABIAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAABkKADAAQAAAABAAABkAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBkAGQAwERAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//E
UPDATED CODE IN THE QUESTION
For now, the code doesn't have force unwrap. But now I always gets standard #imageLiteral(resourceName: "no_prof_image"). (Before, at least jpg works fine :) )
Quite obviously, you use UIImageJPEGRepresentation for .jpeg images, but for .png images you should use UIImagePNGRepresentation
Also, don't use force unwrapping.
static func makeBase64FromImage(image: UIImage) -> String? {
var imageData : Data?
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
imageData = jpegData
} else if let pngData = UIImagePNGRepresentation(image) {
imageData = pngData
}
return imageData?.base64EncodedString()
}
Looks like your issue is your PNG data size which is much bigger than JPEG data. So your server might have a size limit for your image upload.
Regarding your encoding method The second condition else if let pngData = UIImagePNGRepresentation(image) will never be executed. You have to choose which one you would like to use PNG or JPEG data representations (JPEG most times due to the size limit). Btw this would be much easier using optional chaining.
return UIImageJPEGRepresentation(image, 1)?.base64EncodedString()
Swift 4.2 Xcode 10 or later
return image.jpegData(compressionQuality: 1)?.base64EncodedString()
As #mag_zbc suggested, start with:
static func makeBase64FromImage(image: UIImage) -> String? {
var imageData : Data?
if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
imageData = jpegData
} else if let pngData = UIImagePNGRepresentation(image) {
imageData = pngData
}
return imageData?.base64EncodedString()
}
Then, update this code to:
var imageToSend : String = "null"
if profileImage.image != #imageLiteral(resourceName: "no_prof_image"),
let validImage = profileImage.image,
let imageBase64 = AppUtils.makeBase64FromImage(image: validImage) {
imageToSend = imageBase64
}
let parameters : Parameters = [
"image": imageToSend
]
...
In general, you want to avoid using "!" anywhere unless you can 100% confirm that in any and all cases the value will always be defined. In this case, I believe the issue was your code being called with profileImage.image == nil
A profileImage.image being nil would != to the image literal, and therefore would have entered the conditional if you defined. Then by forcing it to be unwrapped with "!" you tried to unwrap nil.
Good luck!
I am trying to use a color mask to make a color in JPG image transparent because as I read, color mask only works with JPG.
This code work when I apply the color mask and save the image as a JPG, but as a JPG, there is no transparency so I want to transform the JPG image to a PNG image to keep the transparency but when I try to do it, the color mask doesn't work.
Am I doing something wrong or maybe this isn't the right approach.
Here is the code of the 2 functions :
func callChangeColorByTransparent(_ sender: UIButton){
var colorMasking: [CGFloat] = []
if let textLabel = sender.titleLabel?.text {
switch textLabel {
case "Remove Black":
colorMasking = [0,30,0,30,0,30]
break
case "Remove Red":
colorMasking = [180,255,0,50,0,60]
break
default:
colorMasking = [222,255,222,255,222,255]
}
}
print(colorMasking)
let newImage = changeColorByTransparent(selectedImage, colorMasking: colorMasking)
symbolImageView.image = newImage
}
func changeColorByTransparent(_ image : UIImage, colorMasking : [CGFloat]) -> UIImage {
let rawImage: CGImage = (image.cgImage)!
//let colorMasking: [CGFloat] = [222,255,222,255,222,255]
UIGraphicsBeginImageContext(image.size)
let maskedImageRef: CGImage = rawImage.copy(maskingColorComponents: colorMasking)!
if let context = UIGraphicsGetCurrentContext() {
context.draw(maskedImageRef, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
var newImage = UIImage(cgImage: maskedImageRef, scale: image.scale, orientation: image.imageOrientation)
UIGraphicsEndImageContext()
var pngImage = UIImage(data: UIImagePNGRepresentation(newImage)!, scale: 1.0)
return pngImage!
}
print("fail")
return image
}
Thank for your help.
Thanks the issue of DonMag in my other question SWIFT 3 - CGImage copy always nil, here is the code to solve this :
func saveImageWithAlpha(theImage: UIImage, destFile: URL) -> Void {
// odd but works... solution to image not saving with proper alpha channel
UIGraphicsBeginImageContext(theImage.size)
theImage.draw(at: CGPoint.zero)
let saveImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
if let img = saveImage, let data = UIImagePNGRepresentation(img) {
try? data.write(to: destFile)
}
}