我看过很多例子,但仍然无法完成我的工作。我正在使用以下代码将我的图像编码为Base64字符串
public static String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.NO_WRAP);
Log.v(Constant.TAG,"Encoded String"+encodedImage);
return encodedImage;
}
当我将这个encodedImage
发布到运行PHP的web服务器时,它不会解码回图像我使用下面的PHP代码测试了它
if ( base64_encode(base64_decode($image, true)) === $image){
echo '$data is valid';
} else {
echo '$data is NOT valid';
}
其中$image已编码字符串。
下面是两件奇怪的事情。
- 在java中编码的字符串在java中是可解码的,我可以将其解码回来并获得位图,并能够成功地使用图像视图显示它
- "=="符号未出现在编码字符串的末尾
请告诉我到底出了什么问题?
下面是base64代码:http://pixyfi.kgcorner.com/uploads/test.txt
以下是上传图像的代码
public static String makePostRequest(String url,String params)
{
String response="";
try {
URL restURL= new URL(url);
HttpURLConnection connection=(HttpURLConnection)restURL.openConnection();
connection.setDoOutput(true);
OutputStream os= connection.getOutputStream();
OutputStreamWriter writer= new OutputStreamWriter(os,"UTF-8");
writer.write(params);
writer.flush();
InputStream is=new BufferedInputStream(connection.getInputStream());
response=convertStreamToString(is);
} catch (MalformedURLException e) {
Log.e(Constant.TAG,e.getMessage(),e);
} catch (IOException e) {
Log.e(Constant.TAG,e.getMessage(),e);
}
return response;
}
param是包含我需要发送到服务器的所有参数的查询字符串。image=&details=
我是如何在php端上获得它的
$image=$_POST['image'];
我如何验证它
if ( base64_encode(base64_decode($image, true)) === $image){
echo "valid";
} else {
echo "NOT valid";
}
输出无效。
终于可以解决了。事实上,我发现java和php都没有问题。以下是在php 中解码图像的最终代码
$image = str_replace(' ','+',$image); //replacing ' ' with '+'
if ( base64_encode(base64_decode($image, true)) === $image){
echo '$data is valid';
} else {
echo '$data is NOT valid';
}