问题:
在通过前端的canvas标签,将其中的图像内容通过toDataURL()方法(其对应的元素的对象调用toDataURL方法)将其内容进行base64编码为字符串之后传到后台,后台在接收到相应的字符串之后,对其进行解码,同时保存为png格式的图片,发现保存的图片无法正确的进行显示。
解决方法:
在后台,解码之后的内容,其“+”符号被替换为了空格,为此,应当将空格替换为“+”之后再写入文件中,图片才能正确的进行显示
相应的后台的代码(java):
/**
* 对ajax传递过来的base64编码的数据进行解码将其保存为png图片
* @param picture 图片所对应的base64编码的字符串
*
*/
public void decode(String picture)
{
byte[] bt=null;
int index=picture.indexOf(",");
picture=picture.substring(index+1,picture.length());//在于去掉首部的非图片的内容的字符串
picture=picture.replaceAll(" ", "+");//关键的语句,当其不将空格转化为"+"时,其解析为png图片时,会出现图片内容无法正确显示的情况
//import sun.misc.BASE64Decoder;
BASE64Decoder decoder=new BASE64Decoder();
try
{
bt=decoder.decodeBuffer(picture);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
OutputStream op=new FileOutputStream(new File(url+pictureName+extendName));
op=new BufferedOutputStream(op);
try
{
op.write(bt);
op.flush();
op.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}