support more base64 decode, for issue #3687

This commit is contained in:
wenshao 2025-08-02 21:02:41 +08:00
parent 0057929154
commit cb4ea2d518
4 changed files with 62 additions and 14 deletions

View File

@ -1885,9 +1885,13 @@ public abstract class JSONReader
public byte[] readBase64() {
String str = readString();
if (str != null) {
String prefix = "data:image/jpeg;base64,";
if (str.startsWith(prefix)) {
str = str.substring(prefix.length());
String prefix = "data:image/";
int p0, p1;
String base64 = "base64";
if (str.startsWith(prefix)
&& (p0 = str.indexOf(';', prefix.length() + 1)) != -1
&& (p1 = str.indexOf(',', p0 + 1)) != -1 && str.regionMatches(p0 + 1, base64, 0, base64.length())) {
str = str.substring(p1 + 1);
}
}
if (str.isEmpty()) {

View File

@ -7463,16 +7463,13 @@ class JSONReaderUTF8
byte[] decoded;
if (index != offset) {
boolean hasPrefix = true;
String prefix = "data:image/jpeg;base64,";
for (int i = 0; i < prefix.length(); i++) {
if (bytes[offset + i] != prefix.charAt(i)) {
hasPrefix = false;
break;
}
}
if (hasPrefix) {
offset += prefix.length();
String prefix = "data:image/";
int p0, p1;
String base64 = "base64";
if (regionMatches(bytes, offset, prefix)
&& (p0 = IOUtils.indexOfChar(bytes, ';', prefix.length() + 1, index)) != -1
&& (p1 = IOUtils.indexOfChar(bytes, ',', p0 + 1, index)) != -1 && IOUtils.regionMatches(bytes, p0 + 1, base64)) {
offset = p1 + 1;
}
byte[] src = Arrays.copyOfRange(bytes, offset, index);

View File

@ -1621,6 +1621,19 @@ public class IOUtils {
return indexOfChar(buf, '\\', i, max);
}
public static boolean regionMatches(byte[] bytes, int off, String prefix) {
int len = prefix.length();
if (off + len >= bytes.length) {
return false;
}
for (int i = 0; i < len; i++) {
if (bytes[off + i] != prefix.charAt(i)) {
return false;
}
}
return true;
}
public static int indexOfChar(byte[] buf, int ch, int fromIndex, int max) {
for (int i = fromIndex; i < max; i++) {
if (buf[i] == ch) {

File diff suppressed because one or more lines are too long