Skip to content

Commit

Permalink
fix: always return correct mimetype for images (capacitor-community#102)
Browse files Browse the repository at this point in the history
This will add support for jpeg images.

Closes capacitor-community#101
  • Loading branch information
tafelnl authored Mar 3, 2023
1 parent 5984044 commit 4aad66c
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
import androidx.annotation.NonNull;
import com.getcapacitor.JSArray;
import com.getcapacitor.JSObject;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLConnection;

public class ContactPayload {

Expand Down Expand Up @@ -52,6 +56,19 @@ public class ContactPayload {
this.contactId = contactId;
}

private static @NonNull String getMimetype(byte[] blob) {
try {
InputStream is = new BufferedInputStream(new ByteArrayInputStream(blob));
String mimeType = URLConnection.guessContentTypeFromStream(is);
if (mimeType == null) {
return "image/png";
}
return mimeType;
} catch (Exception e) {
return "image/png";
}
}

private Integer parseStrToIntSafe(String str) {
try {
return Integer.parseInt(str);
Expand Down Expand Up @@ -90,8 +107,9 @@ private String getBase64ByColumnName(Cursor cursor, String columnName) {
if (index >= 0) {
byte[] blob = cursor.getBlob(index);
if (blob != null) {
String mimeType = getMimetype(blob);
String encodedImage = Base64.encodeToString(blob, Base64.NO_WRAP);
return "data:image/png;base64," + encodedImage;
return "data:" + mimeType + ";base64," + encodedImage;
}
}
return null;
Expand Down
15 changes: 14 additions & 1 deletion ios/Plugin/ContactPayload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,17 @@ public class ContactPayload {
self.contactId = contactId
}

static func getMimetype(_ data: Data) -> String {
var b: UInt8 = 0
data.copyBytes(to: &b, count: 1)
switch b {
case 0xFF:
return "image/jpeg"
default:
return "image/png"
}
}

static func getLabel(_ type: String?, _ rawType: String?) -> String? {
// On Android, a custom label is saved with `type` set to "custom" and a separate `label` attribute.
// On iOS, on the contrary, the custom value is just saved into the `type` attribute.
Expand Down Expand Up @@ -153,7 +164,9 @@ public class ContactPayload {
// Image
if contact.isKeyAvailable(CNContactImageDataKey) {
if let image = contact.imageData {
self.image["base64String"] = "data:image/png;base64,\(image.base64EncodedString())"
let mimeType = ContactPayload.getMimetype(image)
let encodedImage = image.base64EncodedString()
self.image["base64String"] = "data:\(mimeType);base64,\(encodedImage)"
}
}
}
Expand Down

0 comments on commit 4aad66c

Please sign in to comment.