У меня есть следующий метод:Кодирование строки из массива байтов вопроса
/**
* Encodes the byte array into base64 string
* @param imageByteArray - byte array
* @return String a {@link java.lang.String}
*/
public static String encodeImage(byte[] imageByteArray) {
return Base64.encodeBase64URLSafeString(imageByteArray);
}
Я ввожу «org.apache.commons.codec.binary.Base64;» Тем не менее, я получаю ошибку:
Несколько маркеров на этой линии - Метод encodeBase64URLSafeString (байт []) не определено для типа Base64 - линия точек останова: MySQLConnection [линии: 287] - encodeImage (байт [])
Я скопировал этот код с "http://www.myjeeva.com/2012/07/how-to-convert-image-to-string-and-string-to-image-in-java/". Я использую Eclipse Juno (полностью обновленный) и GWT.
Кто-нибудь знает, что я делаю неправильно здесь?
С уважением,
Глин
Спасибо Маркус А. Теперь я создал этот класс из вашей информации:
package org.AwardTracker.server;
public class Base64Decode {
private final static String base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/";
public static byte[] decode(String s) {
// remove/ignore any characters not in the base64 characters list
// or the pad character -- particularly newlines
s = s.replaceAll("[^" + base64chars + "=]", "");
// replace any incoming padding with a zero pad (the 'A' character is
// zero)
String p = (s.charAt(s.length() - 1) == '=' ? (s.charAt(s.length() - 2) == '=' ? "AA"
: "A")
: "");
s = s.substring(0, s.length() - p.length()) + p;
int resLength = (int) Math.ceil(((float) (s.length())/4f) * 3f);
byte[] bufIn = new byte[resLength];
int bufIn_i = 0;
// increment over the length of this encrypted string, four characters
// at a time
for (int c = 0; c < s.length(); c += 4) {
// each of these four characters represents a 6-bit index in the
// base64 characters list which, when concatenated, will give the
// 24-bit number for the original 3 characters
int n = (base64chars.indexOf(s.charAt(c)) << 18)
+ (base64chars.indexOf(s.charAt(c + 1)) << 12)
+ (base64chars.indexOf(s.charAt(c + 2)) << 6)
+ base64chars.indexOf(s.charAt(c + 3));
// split the 24-bit number into the original three 8-bit (ASCII)
// characters
char c1 = (char) ((n >>> 16) & 0xFF);
char c2 = (char) ((n >>>8) & 0xFF);
char c3 = (char) (n & 0xFF);
bufIn[bufIn_i++] = (byte) c1;
bufIn[bufIn_i++] = (byte) c2;
bufIn[bufIn_i++] = (byte) c3;
}
return bufIn;
}
}
И изменил вызов: импорта org.AwardTracker.server .Base64Decode;
public static String encodeImage(byte[] imageByteArray) {
return Base64Decode(imageByteArray); [Error on this line]
}
А теперь я получаю ошибку:
Несколько маркеров на этой линии - Метод Base64Decode (байт []) не определено для типа MySQLConnection
Помощь greatfuly оценили.
С уважением,
Глин
Круглых Три
КАМИ, так что у меня было шифровать и дешифровать Arround неправильного пути. Теперь это исправлено и помещено в правильные библиотеки. Однако у меня все еще есть ошибка в методе encodeImage. Это метод, который я использую для вызова метода encodeImage. Я подозреваю, что линии:
java.sql.Blob imageBlob = result.getBlob(1);
byte[] imageData = imageBlob.getBytes(1, (int) imageBlob.length());
неверны. Тем не менее, я определил ImageData как байт [], поэтому я не понимаю, почему encodeImage считает, что это String?
public String getImageData(String id){
ResultSet result = null;
PreparedStatement ps = null;
String imageDataString = null;
try {
// Read in the image from the database.
ps = conn.prepareStatement(
"SELECT at_cub_details.cd_photograph " +
"FROM at_cub_details " +
"WHERE at_cub_details.cd_id = \"" + id + "\"");
result = ps.executeQuery();
while (result.next()) {
java.sql.Blob imageBlob = result.getBlob(1);
byte[] imageData = imageBlob.getBytes(1, (int) imageBlob.length());
//Convert Image byte array into Base64 String
imageDataString = encodeImage(imageData);
}
}
Результирующая с ошибкой в:
public static String encodeImage(byte[] imageByteArray) {
return Base64Encode.encode(imageByteArray); [Error on this line]
}
из "Метод кодирования (String) в типа Base64Encode не применяется для аргументов (Byte [])"
Спасибо за всю вашу помощь.
С уважением,
Глин
P.S., Я думаю, что это будет заслуживать блог, когда я закончу, поскольку я не могу найти какой-либо определенной работы в этой области, и я бы подумал, что это будет использоваться очень часто. Мой следующий проект.
Класс Encode является:
package org.AwardTracker.server;
public class Base64Encode {
private final static String base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/";
public static String encode(String s) {
// the result/encoded string, the padding string, and the pad count
String r = "", p = "";
int c = s.length() % 3;
// add a right zero pad to make this string a multiple of 3 characters
if (c > 0) {
for (; c < 3; c++) {
p += "=";
s += "\0";
}
}
// increment over the length of the string, three characters at a time
for (c = 0; c < s.length(); c += 3) {
// we add newlines after every 76 output characters, according to
// the MIME specs
if (c > 0 && (c/3 * 4) % 76 == 0)
r += "\r\n";
// these three 8-bit (ASCII) characters become one 24-bit number
int n = (s.charAt(c) << 16) + (s.charAt(c + 1) << 8)
+ (s.charAt(c + 2));
// this 24-bit number gets separated into four 6-bit numbers
int n1 = (n >> 18) & 63, n2 = (n >> 12) & 63, n3 = (n >> 6) & 63, n4 = n & 63;
// those four 6-bit numbers are used as indices into the base64
// character list
r += "" + base64chars.charAt(n1) + base64chars.charAt(n2)
+ base64chars.charAt(n3) + base64chars.charAt(n4);
}
return r.substring(0, r.length() - p.length()) + p;
}
}
А класс Decode является:
package org.AwardTracker.server;
public class Base64Decode {
private final static String base64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/";
public static byte[] decode(String s) {
// remove/ignore any characters not in the base64 characters list
// or the pad character -- particularly newlines
s = s.replaceAll("[^" + base64chars + "=]", "");
// replace any incoming padding with a zero pad (the 'A' character is
// zero)
String p = (s.charAt(s.length() - 1) == '=' ? (s.charAt(s.length() - 2) == '=' ? "AA"
: "A")
: "");
s = s.substring(0, s.length() - p.length()) + p;
int resLength = (int) Math.ceil(((float) (s.length())/4f) * 3f);
byte[] bufIn = new byte[resLength];
int bufIn_i = 0;
// increment over the length of this encrypted string, four characters
// at a time
for (int c = 0; c < s.length(); c += 4) {
// each of these four characters represents a 6-bit index in the
// base64 characters list which, when concatenated, will give the
// 24-bit number for the original 3 characters
int n = (base64chars.indexOf(s.charAt(c)) << 18)
+ (base64chars.indexOf(s.charAt(c + 1)) << 12)
+ (base64chars.indexOf(s.charAt(c + 2)) << 6)
+ base64chars.indexOf(s.charAt(c + 3));
// split the 24-bit number into the original three 8-bit (ASCII)
// characters
char c1 = (char) ((n >>> 16) & 0xFF);
char c2 = (char) ((n >>>8) & 0xFF);
char c3 = (char) (n & 0xFF);
bufIn[bufIn_i++] = (byte) c1;
bufIn[bufIn_i++] = (byte) c2;
bufIn[bufIn_i++] = (byte) c3;
}
return bufIn;
}
}
я, наконец, нашел класс кодирования, который работает:
package org.AwardTracker.server;
public class Base64Encode2 {
private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/".toCharArray();
private static int[] toInt = new int[128];
static {
for(int i=0; i< ALPHABET.length; i++){
toInt[ALPHABET[i]]= i;
}
}
/**
* Translates the specified byte array into Base64 string.
*
* @param buf the byte array (not null)
* @return the translated Base64 string (not null)
*/
public static String encode(byte[] buf){
int size = buf.length;
char[] ar = new char[((size + 2)/3) * 4];
int a = 0;
int i=0;
while(i < size){
byte b0 = buf[i++];
byte b1 = (i < size) ? buf[i++] : 0;
byte b2 = (i < size) ? buf[i++] : 0;
int mask = 0x3F;
ar[a++] = ALPHABET[(b0 >> 2) & mask];
ar[a++] = ALPHABET[((b0 << 4) | ((b1 & 0xFF) >> 4)) & mask];
ar[a++] = ALPHABET[((b1 << 2) | ((b2 & 0xFF) >> 6)) & mask];
ar[a++] = ALPHABET[b2 & mask];
}
switch(size % 3){
case 1: ar[--a] = '=';
case 2: ar[--a] = '=';
}
return new String(ar);
}
}
Спасибо за вашу помощь. Маркус А. Очень благодарен.
С уважением,
Глин
у вас есть правильная версия Base64, так как методы несколько раз менялись. Убедитесь, что у вас есть версия yo. –
Вы кодируете массив байтов (который является изображением?) С помощью URL-кодера ??? – texasbruce