我使用ostermillerutils库创建base64字符串,但是如果图像很重,则会出现OutOfMemory错误。如果我尝试转换的图像是简单图像,则代码工作正常。
public String createBase64String(InputStream in) { //collect = new ByteArrayOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; try { for(int readNum; (readNum = in.read(buf)) != -1; ) { bos.write(buf, 0, readNum); } } catch (IOException ex) { Logger.getInstance().debug("XML createBase64String: IOException"); return null; } finally { if (in != null) { try { in.close(); } catch (IOException ex) { ; } } } byte[] ba = bos.toByteArray(); String coded = Base64.encodeToString(ba); return coded; }
我也尝试这样做,但是当我尝试对它进行解码时,base64是不正确的。
public void createBase64String(InputStream in) throws IOException { //collect = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; int readNum = 0; try { while((readNum = in.read(buf)) != -1) { smtp.addBase64(Base64.encodeBase64String(buf)); } } catch (IOException ex) { Logger.getInstance().debug("XML createBase64String: IOException"); } finally { if (in != null) { in.close(); } } }
请为JDK 1.4和更高版本的Java建议解决方案。
我通过使用javabase64-1.3.1.jar库解决了我的问题。
OutputStream fos2 = FileUtil.getOutputStream(base64FileName, FileUtil.HDD); InputStream in2 = FileUtil.getInputStream(fileName, FileUtil.HDD); Base64.encode(in2, fos2); in2.close(); fos2.close();
我首先将base64字符串存储到文本文件中。
public void createBase64String(InputStream in) throws IOException { baos = new ByteArrayOutputStream(); byte[] buf = new byte[BUFFER_SIZE]; int readNum = 0; smtp.addBase64("\t\t"); try { while ((readNum = in.read(buf)) >= 0) { baos.write(buf, 0, readNum); smtp.addBase64(baos.toString()); baos.reset(); } } catch (IOException ex) { LogUtil.error("Sending of Base64 String to SMTP: IOException: " + ex); } finally { if (in != null) { in.close(); baos.close(); } } baos = null; buf = null; }
然后将每行发送到smtp的套接字输出流。