0

I am trying to generate a base64 string from the same image in swift and c#, come out the base64 string are different but similar, is it suppose the base64 string should be same if generated from the same image?

The base64 string result in swift
/9j/4AAQSkZJRgABAQAASABIAAD/..................

The base64 string result in c#
/9j/4AAQSkZJRgABAQEAYABgAAD/..................

And i have proved that one from swift is invalid base64 string, that one from c# is valid. is it any problem on my swift script?


//swift

let image : UIImage = UIImage(named:"a.jpg")!
var strBase64 = image.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""


//c#

private string GenString()
{
    byte[] bytes = GetFileByteArray(@"C:\temp\a.jpg");

    return Convert.ToBase64String(bytes);
}

private byte[] GetFileByteArray(string filename)
{
     FileStream oFileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
     byte[] FileByteArrayData = new byte[oFileStream.Length];            
     oFileStream.Read(FileByteArrayData, 0, System.Convert.ToInt32(oFileStream.Length));
     oFileStream.Close();

     return FileByteArrayData;
}
user3721070
  • 151
  • 2
  • 8

2 Answers2

2

This thread is old, but I want to post answers as the existing one is not correct, in my opinion

The Swift code is doing an extra compression on the original image, unlike directly reading the image file in the C# code. Even though the quality is set to 100%, you may have potentially altered the image data.

I recommend to use Data class (Swift bridging equivalent to NSData) to read in the image file unaltered, with this constructor specifically: https://developer.apple.com/documentation/foundation/data/3126626-init

...then you can get the base-64 string from the Data class using base64EncodedString(options:)

As for how to retrieve the file path URL, use Bundle to locate resources in the app bundle. Assuming your a.jpg are simply copied into the app bundle root during build, simply use this method: https://developer.apple.com/documentation/foundation/bundle/1411540-url

// Swift 5.1
let url = Bundle.main.url(forResource: "a" withExtension:"jpg")
heshuimu
  • 144
  • 1
  • 10
0

Try Using below code to convert your image into Base64 string.

    func ImageToBase64String(format: ImageType, image:UIImage) -> String? {
        var imageBase64Data: Data?
        switch format {
        case .png: imageBase64Data = UIImagePNGRepresentation(image)
        case .jpeg(let compression): imageBase64Data = UIImageJPEGRepresentation(image, 
        compression)
       }
          return imageBase64Data?.base64EncodedString()
      }

public enum ImageType {
    case png
    case jpeg(CGFloat)
}

Calling code for the function

    let image = UIImage(named:"name of your image")
    let base64String = ImageToBase64String(format: .png, image: image!)