| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
package com.drew.metadata.iptc; |
| 22 |
|
| 23 |
import com.drew.lang.annotations.NotNull; |
| 24 |
import com.drew.lang.annotations.Nullable; |
| 25 |
|
| 26 |
import java.nio.ByteBuffer; |
| 27 |
import java.nio.charset.CharacterCodingException; |
| 28 |
import java.nio.charset.Charset; |
| 29 |
import java.nio.charset.CharsetDecoder; |
| 30 |
|
| 31 |
public final class Iso2022Converter |
| 32 |
{ |
| 33 |
private static final String ISO_8859_1 = "ISO-8859-1"; |
| 34 |
private static final String UTF_8 = "UTF-8"; |
| 35 |
|
| 36 |
private static final byte LATIN_CAPITAL_A = 0x41; |
| 37 |
private static final int DOT = 0xe280a2; |
| 38 |
private static final byte LATIN_CAPITAL_G = 0x47; |
| 39 |
private static final byte PERCENT_SIGN = 0x25; |
| 40 |
private static final byte MINUS_SIGN = 0x2D; |
| 41 |
private static final byte DOT_SIGN = 0x2E; |
| 42 |
private static final byte ESC = 0x1B; |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
@Nullable |
| 52 |
public static String convertISO2022CharsetToJavaCharset(@NotNull final byte[] bytes) |
| 53 |
{ |
| 54 |
if (bytes.length > 2 && bytes[0] == ESC && bytes[1] == PERCENT_SIGN && bytes[2] == LATIN_CAPITAL_G) |
| 55 |
return UTF_8; |
| 56 |
|
| 57 |
if (bytes.length > 2 && bytes[0] == ESC && bytes[1] == DOT_SIGN && bytes[2] == LATIN_CAPITAL_A) |
| 58 |
return ISO_8859_1; |
| 59 |
|
| 60 |
if (bytes.length > 3 && bytes[0] == ESC && (bytes[3] & 0xFF | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF) << 16)) == DOT && bytes[4] == LATIN_CAPITAL_A) |
| 61 |
return ISO_8859_1; |
| 62 |
|
| 63 |
if (bytes.length > 2 && bytes[0] == ESC && bytes[1] == MINUS_SIGN && bytes[2] == LATIN_CAPITAL_A) |
| 64 |
return ISO_8859_1; |
| 65 |
|
| 66 |
return null; |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
@Nullable |
| 90 |
static Charset guessCharSet(@NotNull final byte[] bytes) |
| 91 |
{ |
| 92 |
String[] encodings = { UTF_8, System.getProperty("file.encoding"), ISO_8859_1 }; |
| 93 |
|
| 94 |
for (String encoding : encodings) |
| 95 |
{ |
| 96 |
Charset charset = Charset.forName(encoding); |
| 97 |
CharsetDecoder cs = charset.newDecoder(); |
| 98 |
|
| 99 |
try { |
| 100 |
cs.decode(ByteBuffer.wrap(bytes)); |
| 101 |
return charset; |
| 102 |
} catch (CharacterCodingException e) { |
| 103 |
|
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
|
| 108 |
return null; |
| 109 |
} |
| 110 |
|
| 111 |
private Iso2022Converter() |
| 112 |
{} |
| 113 |
} |