2

I am developing an application by Swift for Iphone / Ipad. It is an adaptation of an Android application. Problem is : I have a UIImage I resized. I want to convert this to a String to send a request on a PHP server. I have already made in Android

public static String BitMapToString(Bitmap bitmap) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] b = baos.toByteArray();
    String temp = Base64.encodeToString(b, Base64.DEFAULT);
    return temp;
}

The String returned is read and stored as image in the server for PHP script:

$lienphoto = "adressesurleserveur".$nomimage;
$binary=base64_decode($image);
$fichier = fopen($lienphoto, 'wb');
fwrite($fichier, $binary);
fclose($fichier);

I want to do the same with swift, I have already tried:

var imageData = UIImageJPEGRepresentation(imageChoisie, 1.0)
let base64String = imageData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

and base64String correspond to String that PHP receives. This does not work, the created file is "corrupted". I try other ways for a few hours but I have no solution yet. I found no forums posts with a response to this problem.

In advance thank you for the time you will grant me.

1 Answer 1

1

I found a solution.

The amendment is made in the php script:

 $lienphoto = "adresse sur serveur".$nomimage;

$data = str_replace('data:image/jpg;base64,', '', $image);

$data = str_replace(' ', '+', $data);

$data = base64_decode($data);

$success = file_put_contents($lienphoto, $data);

This approach is proposed on the site:

http://www.tricksofit.com/2014/10/save-base64-encoded-image-to-file-using-php

This keeps the Swift and Android code. I just have to create two php scripts for saving the image.

Sign up to request clarification or add additional context in comments.

1 Comment

What Swift code did you use to get the base64 encoded string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.