将图片转成base64字符串并在JSP页面显示的Java代码
JS实现对中文字符串进行utf-8的Base64编码的方法(使其与Java编码相同)
JS实现对中⽂字符串进⾏utf-8的Base64编码的⽅法(使其与Java编码相同)本⽂实例讲述了JS实现对中⽂字符串进⾏utf-8的Base64编码的⽅法。
分享给⼤家供⼤家参考,具体如下:要进⾏编码的字符串:“select ⽤户名 from ⽤户”使⽤JAVA进⾏编码,Java程序:String sql = "select ⽤户名 from ⽤户";String encodeStr = new String(Base64.encode(sql.getBytes("UTF-8"))); // 编码System.out.println(encodeStr);得到:c2VsZWN0IOeUqOaIt+WQjSBmcm9tIOeUqOaItw==在Java中解码:sql = new String(Base64.decode(sql.getBytes()), "UTF-8");Java代码中为什么要使⽤getBytes("UTF-8")呢?因为Windows和Linux环境下默认编码不同,要使你的程序在不同平台下得到相同编码,必然要指定编码虽然Html和JS的编码都是utf-8,但JS从页⾯上得到的中⽂编码却是utf-16,所以直接对中⽂进⾏Base64编码将得到错误的结果,所以我们要先从utf-16转到utf-8再编码<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><title></title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style type="text/css"><!--body{margin:0px;padding:0px;}body,td{font-size:9pt;}--></style><script type="text/JavaScript"><!--var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";//将Ansi编码的字符串进⾏Base64编码function encode64(input) {var output = "";var chr1, chr2, chr3 = "";var enc1, enc2, enc3, enc4 = "";var i = 0;do {chr1 = input.charCodeAt(i++);chr2 = input.charCodeAt(i++);chr3 = input.charCodeAt(i++);enc1 = chr1 >> 2;enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);enc4 = chr3 & 63;if (isNaN(chr2)) {enc3 = enc4 = 64;} else if (isNaN(chr3)) {enc4 = 64;}output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)+ keyStr.charAt(enc3) + keyStr.charAt(enc4);chr1 = chr2 = chr3 = "";enc1 = enc2 = enc3 = enc4 = "";} while (i < input.length);return output;}//将Base64编码字符串转换成Ansi编码的字符串function decode64(input) {var output = "";var chr1, chr2, chr3 = "";var enc1, enc2, enc3, enc4 = "";var i = 0;if (input.length % 4 != 0) {return "";}var base64test = /[^A-Za-z0-9\+\/\=]/g;if (base64test.exec(input)) {return "";}do {enc1 = keyStr.indexOf(input.charAt(i++));enc2 = keyStr.indexOf(input.charAt(i++));enc3 = keyStr.indexOf(input.charAt(i++));enc4 = keyStr.indexOf(input.charAt(i++));chr1 = (enc1 << 2) | (enc2 >> 4);chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);chr3 = ((enc3 & 3) << 6) | enc4;output = output + String.fromCharCode(chr1);if (enc3 != 64) {output += String.fromCharCode(chr2);}if (enc4 != 64) {output += String.fromCharCode(chr3);}chr1 = chr2 = chr3 = "";enc1 = enc2 = enc3 = enc4 = "";} while (i < input.length);return output;}function utf16to8(str) {var out, i, len, c;out = "";len = str.length;for(i = 0; i < len; i++) {c = str.charCodeAt(i);if ((c >= 0x0001) && (c <= 0x007F)) {out += str.charAt(i);} else if (c > 0x07FF) {out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));} else {out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));}}return out;}function utf8to16(str) {var out, i, len, c;var char2, char3;out = "";len = str.length;i = 0;while(i < len) {c = str.charCodeAt(i++);switch(c >> 4) {case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxxout += str.charAt(i-1);break;case 12: case 13:// 110x xxxx 10xx xxxxchar2 = str.charCodeAt(i++);out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break;case 14:// 1110 xxxx 10xx xxxx 10xx xxxxchar2 = str.charCodeAt(i++);char3 = str.charCodeAt(i++);out += String.fromCharCode(((c & 0x0F) << 12) |((char2 & 0x3F) << 6) |((char3 & 0x3F) << 0));break;}}return out;}// 测试代码开始var de = encode64(utf16to8("select ⽤户名 from ⽤户"));document.writeln(de+"<br>");var ee = utf8to16(decode64(de))document.writeln(ee);// 测试代码结束//--></script></head><body></body></html>上⾯的代码都是从⽹上得来,拼凑后得到正确结果,在此感谢前辈们PS:这⾥再为⼤家推荐⼏款base64编码解码在线⼯具,相信在以后的开发中会⽤得到:更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家JavaScript程序设计有所帮助。
java中图片上传并在jsp页面显示
image mediumblob not null,
description varchar(100) null
);
5,应用程序的目录结构
%catalina_home%\webapps\demo
------test_upload.htm
------upload.jsp
------WEB-INF
|-------commons-fileupload-1.0.jar
|----src
|----com
|-----cf
<html>
<head>
<title>
上传测试
</title>
<body>
<form action="upload.jsp" enctype="multipart/form-data" method="post">
your name:
<br>
<input type="text" name="name">
6,web.xml文件内容
<?xml version="1.0"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"/j2ee/dtds/web-app_2_3.dtd">
<%
DiskFileUpload upload=new DiskFileUpload();
Java图片与byte数组互相转换
Java图⽚与byte数组互相转换 1//图⽚到byte数组2public byte[] image2byte(String path){3byte[] data = null;4 FileImageInputStream input = null;5try {6 input = new FileImageInputStream(new File(path));7 ByteArrayOutputStream output = new ByteArrayOutputStream();8byte[] buf = new byte[1024];9int numBytesRead = 0;10while ((numBytesRead = input.read(buf)) != -1) {11 output.write(buf, 0, numBytesRead);12 }13 data = output.toByteArray();14 output.close();15 input.close();16 }17catch (FileNotFoundException ex1) {18 ex1.printStackTrace();19 }20catch (IOException ex1) {21 ex1.printStackTrace();22 }23return data;24 }1//byte数组到图⽚2public void byte2image(byte[] data,String path){3if(data.length<3||path.equals("")) return;4try{5 FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));6 imageOutput.write(data, 0, data.length);7 imageOutput.close();8 System.out.println("Make Picture success,Please find image in " + path);9 } catch(Exception ex) {10 System.out.println("Exception: " + ex);11 ex.printStackTrace();12 }13 }14//byte数组到16进制字符串15public String byte2string(byte[] data){16if(data==null||data.length<=1) return "0x";17if(data.length>200000) return "0x";18 StringBuffer sb = new StringBuffer();19int buf[] = new int[data.length];20//byte数组转化成⼗进制21for(int k=0;k<data.length;k++){22 buf[k] = data[k]<0?(data[k]+256):(data[k]);23 }24//⼗进制转化成⼗六进制25for(int k=0;k<buf.length;k++){26if(buf[k]<16) sb.append("0"+Integer.toHexString(buf[k]));27else sb.append(Integer.toHexString(buf[k]));28 }29return "0x"+sb.toString().toUpperCase();30 }⽂件解析:FileImageOutputStream 换成了 FileOutputStreamFileImageInputStream 换成 FileInputStream转⾃:/huang9012/article/details/18241539/。
JavaScript实现Base64编码转换
JavaScript实现Base64编码转换简介Base64是⼀种基于64个可打印字符来表⽰⼆进制数据的表⽰⽅法。
由于2的6次⽅等于64,所以每6个⽐特为⼀个单元,对应某个可打印字符。
三个字节有24个⽐特,对应于4个Base64单元,即3个字节需要⽤4个可打印字符来表⽰。
它可⽤来作为电⼦邮件的传输编码。
在Base64中的可打印字符包括字母A-Z、a-z、数字0-9,这样共有62个字符,此外的两个可打印符号在不同的系统中⽽不同,⼀般为+和/。
转换原理Base64的直接数据源是⼆进制序列(Binary Sequence)。
当然,你也可以将图⽚、⽂本和⾳视频转换成⼆进制序列,再然后转换为Base64编码。
我们这⾥讨论的是如何将⼆进制转换为Base64编码,对于如何将图⽚,⽂本和⾳视频转换为⼆进制序列敬请期待。
在转换前,先定义⼀张索引表,这张表规定了如何转换:转换的时候我们先将⼆进制序列分组,每6个⽐特为⼀组。
但是如果编码的字节数不能被3整除,那么最后就会多出1个或两个字节,可以使⽤下⾯的⽅法进⾏处理:先使⽤0字节值在末尾补⾜,使其能够被3整除,然后再进⾏base64的编码。
在编码后的base64⽂本后加上⼀个或两个'='号,代表补⾜的字节数。
也就是说,当最后剩余⼀个⼋位字节(⼀个byte)时,最后⼀个6位的base64字节块有四位是0值,最后附加上两个等号;如果最后剩余两个⼋位字节(2个byte)时,最后⼀个6位的base字节块有两位是0值,最后附加⼀个等号。
参考下表:JavaScript实现Base64原理明⽩了以后,实现起来就很容易了。
define(function(require, exports, module) {var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); //索引表 /*** @author laixiangran@* @description 将⼆进制序列转换为Base64编码* @param {String}* @return {String}*/function binToBase64(bitString) {var result = "";var tail = bitString.length % 6;var bitStringTemp1 = bitString.substr(0, bitString.length - tail);var bitStringTemp2 = bitString.substr(bitString.length - tail, tail);for (var i = 0; i < bitStringTemp1.length; i += 6) {var index = parseInt(bitStringTemp1.substr(i, 6), 2);result += code[index];}bitStringTemp2 += new Array(7 - tail).join("0");if (tail) {result += code[parseInt(bitStringTemp2, 2)];result += new Array((6 - tail) / 2 + 1).join("=");}return result;}/*** @author laixiangran@* @description 将base64编码转换为⼆进制序列* @param {String}* @return {String}*/function base64ToBin(str) {var bitString = "";var tail = 0;for (var i = 0; i < str.length; i++) {if (str[i] != "=") {var decode = code.indexOf(str[i]).toString(2);bitString += (new Array(7 - decode.length)).join("0") + decode;} else {tail++;}}return bitString.substr(0, bitString.length - tail * 2);}/*** @author laixiangran@* @description 将字符转换为⼆进制序列* @param {String} str* @return {String}*/function stringToBin(str) {var result = "";for (var i = 0; i < str.length; i++) {var charCode = str.charCodeAt(i).toString(2);result += (new Array(9 - charCode.length).join("0") + charCode);}return result;}/*** @author laixiangran@* @description 将⼆进制序列转换为字符串* @param {String} Bin*/function BinToStr(Bin) {var result = "";for (var i = 0; i < Bin.length; i += 8) {result += String.fromCharCode(parseInt(Bin.substr(i, 8), 2));}return result;}exports.base64 = function(str) {return binToBase64(stringToBin(str));}exports.decodeBase64 = function(str) {return BinToStr(base64ToBin(str));}})将图⽚数据进⾏Base64编码将图⽚数据转换为Base64,⾸先要获取到图⽚的⼆进制数据。
base64字符串还原成原图片
base64字符串还原成原图⽚今天做⼀个截图上传到ftp服务器的功能,⽤的是jquery插件cropbox.js,后台使⽤的springmvc@RequestMapping("/saveProductInfo")public ModelAndView uploadPreviewImage(HttpServletRequest request,AbcTourProduct product,ScheduleVO scheduleVO) throws IOException{ ModelAndView modelAndView=new ModelAndView(); //1.⽂件上传 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request; MultipartFile smallMutiFile = multipartRequest.getFile("upload-file"); MultipartFile bigMutiFile = multipartRequest.getFile("upload-file2"); String fileName1= smallMutiFile.getOriginalFilename(); String fileName2= bigMutiFile.getOriginalFilename(); int i1=stIndexOf("."); String name1=fileName1.substring(0, i1); String suffix1=fileName1.substring(i1); String smallName=name1+UUID.randomUUID().toString()+suffix1; int i2=stIndexOf("."); String name2=fileName2.substring(0, i2); String suffix2=fileName2.substring(i2); String bigName=name2+UUID.randomUUID().toString()+suffix2; File smallFile=FileUtil.multipartFileToFile(smallMutiFile); File bigFile=FileUtil.multipartFileToFile(bigMutiFile); boolean success1=FileUtil.ftpUpload(smallFile, smallName, "/journey/product/"); boolean success2=FileUtil.ftpUpload(bigFile, bigName, "/journey/product/"); if(success1&&success2){ String smallSrc="/journey/product/"+ smallName; String bigSrc="/journey/product/"+ bigName; product.setProImgUrl(bigSrc); product.setProSmallImgUrl(smallSrc); //新增产品 List<AbcSchedule>scheduleList =scheduleVO.getScheduleVOs(); productService.insertSelective(product, scheduleList); } return modelAndView;}这样做了之后,controller中获得的是原图⽽不是截图,于是我去看插件的实现,发现截图后的图⽚的src是base64的⼀串字符串,⾮常长,如下图只是⼀⼩部分:然后我就想着怎样把这⼀串的字符串在后台转成图⽚进⾏上传,做了⼀个⼩栗⼦:package com.admin.controller;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import .util.Base64;import org.springframework.stereotype.Controller;import org.springframework.util.FileCopyUtils;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import org.springframework.web.servlet.ModelAndView;@RequestMapping("/saveProductInfo")public void uploadPreviewImage(String base64Str) throws IOException{ int start = base64Str.indexOf(',') + 1; base64Str=base64Str.substring(start);//注意:需要将头部的给去掉 byte[] bytes=Base64.decodeBase64(base64Str); for (int i = 0; i < bytes.length; ++i) { if (bytes[i] < 0) {// 调整异常数据 bytes[i] += 256; } } OutputStream outputStream=new FileOutputStream("d://aaa"); outputStream.write(bytes); outputStream.flush(); outputStream.close();}对,就是这样,然后再⽤File取这个图⽚,在进⾏上传的相关步骤注意引⼊的Base64的包,maven坐标是这个<dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.7</version></dependency>话说,这个东西花费了我⼤半天的功夫,,,主要原因是在截取去掉base64字符串的头部的的时候多算了⼀位导致⽣成的图⽚⼀直是损坏⽆法打开的,特此,mark⼀下=====================================================================================================在出问题的时候在技术群问了,有两点启发1.通过base64字符串不能获得原图⽚的后缀,所以巧妙的⽅法是不写后缀,因为图⽚都是在web端查看的,所以不写后缀的话会选择合适的形式来打开2.另外⼀哥们⼉写过的代码,还没仔细看,先存档⼀下。
图片和base64编码字符串互相转换,图片和byte数组互相转换
图⽚和base64编码字符串互相转换,图⽚和byte数组互相转换图⽚和base64编码字符串互相转换import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.io.*;/*** @author lishupeng* @create 2017-05-06 下午 2:56**/public class Base64Test {public static void main(String[] args) {String strImg = GetImageStr();System.out.println(strImg);GenerateImage(strImg);}//图⽚转化成base64字符串public static String GetImageStr() {//将图⽚⽂件转化为字节数组字符串,并对其进⾏Base64编码处理String imgFile = "C:\\Users\\Administrator\\Desktop\\a\\1.png";//待处理的图⽚InputStream in = null;byte[] data = null;//读取图⽚字节数组try {in = new FileInputStream(imgFile);data = new byte[in.available()];in.read(data);in.close();} catch (IOException e) {e.printStackTrace();}//对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);//返回Base64编码过的字节数组字符串}//base64字符串转化成图⽚public static boolean GenerateImage(String imgStr) { //对字节数组字符串进⾏Base64解码并⽣成图⽚if (imgStr == null) //图像数据为空return false;BASE64Decoder decoder = new BASE64Decoder();try {//Base64解码byte[] b = decoder.decodeBuffer(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {//调整异常数据b[i] += 256;}}//⽣成jpeg图⽚String imgFilePath = "d://222.jpg";//新⽣成的图⽚OutputStream out = new FileOutputStream(imgFilePath);out.write(b);out.flush();out.close();return true;} catch (Exception e) {return false;}}图⽚和byte数组互相转换import javax.imageio.stream.FileImageInputStream;import javax.imageio.stream.FileImageOutputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;/*** @author lishupeng* @create 2017-05-06 下午 3:48**/public class Image2Byte {public static void main(String[] args){byte[] data = image2byte("C:\\Users\\Administrator\\Desktop\\a\\1.png");System.out.println(data.toString());byte2image(data,"d://222.jpg");}//图⽚到byte数组public static byte[] image2byte(String path) {byte[] data = null;FileImageInputStream input = null;try {input = new FileImageInputStream(new File(path));ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buf = new byte[1024];int numBytesRead = 0;while ((numBytesRead = input.read(buf)) != -1) {output.write(buf, 0, numBytesRead);}data = output.toByteArray();output.close();input.close();} catch (FileNotFoundException ex1) {ex1.printStackTrace();} catch (IOException ex1) {ex1.printStackTrace();}return data;}//byte数组到图⽚public static void byte2image(byte[] data, String path) {if (data.length < 3 || path.equals("")) return;try {FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path)); imageOutput.write(data, 0, data.length);imageOutput.close();System.out.println("Make Picture success,Please find image in " + path);} catch (Exception ex) {System.out.println("Exception: " + ex);ex.printStackTrace();}}//byte数组到16进制字符串public String byte2string(byte[] data) {if (data == null || data.length <= 1) return "0x";if (data.length > 200000) return "0x";StringBuffer sb = new StringBuffer();int buf[] = new int[data.length];//byte数组转化成⼗进制for (int k = 0; k < data.length; k++) {buf[k] = data[k] < 0 ? (data[k] + 256) : (data[k]);}//⼗进制转化成⼗六进制for (int k = 0; k < buf.length; k++) {if (buf[k] < 16) sb.append("0" + Integer.toHexString(buf[k]));else sb.append(Integer.toHexString(buf[k]));}return "0x" + sb.toString().toUpperCase();}}。
C++读写图片数据转成Base64格式
C++读写图⽚数据转成Base64格式最近在⼀个项⽬中要实现前端传递给我们客户端的是base64的图⽚数据流,我们需要做的就是将它转为图⽚并且保存起来,根据需要再将图⽚存储路径信息做进⼀步操作。
前端传过来的字符串是这样的:<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAAwCAMAAAChd4FcAAAAA3NCSVQICAjb4U/gAAACRlBMVEUAAADi6OSMjIxSUlIrXja5trg8rFEDRhErokJ8w4pJrVxmZmYERRIinTn++P07nk/X0Naww7Stra0pdTj37/d BAsXzdni24VmC7MzMw1kEYzMzPZ4Nul1K6Wr5tWs2jp8eseaC0ufz5mZmaEoorI1cszpUkXTSJErFix2bi1tbVKSkp7e3skWC9wvn5zlHq6yL3S3dSXzqJBcEspKSnY6dxCQkLI486mvKulpaVAbUkTSx8ICAgjcDIhISHh7eM6Ojonnz1QsGP///+Dxo9R x5wYYcYyodmzViuHPFxcVEtFl5mH/V3def0qlhh2rZ7d7F2MiEhIQ4Z0Lv8+/F4csvo0QbUidAp1OEoIoqfDozZjOx27kOSho6mkw2j0iftaMyi0S2xroSUiBrvHuFx5J0v4Lm7+eNqJOc0KVBq1TU59gpoEBskXRzc3Pg2N6tubDe5d99nYRNr1+ZmZkbWyg9 0xbfAz8OtvbUhazC12ryJpY6+3sXD0MbE4MmJyJUgVCtSsmXQ5tWjuKd5wobd8OEfY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rHf7GRr8OhB1HXTwCodaJgzX8yl1BpxMRlTCUgNkYb88WhYw7nQD1J9bpTwOKjf+aCXQ7IOA9dsDxCNAoTqaAbgDdi/EaUvKICoqEFYHNfZ UVepgt1+l4LUBYOzy+3O6/CC7i5MAjSaBa3SgQw3A5emOHW75aHeFFQhzgdrCfUQcexp4rn5rAmIGlkZ+5VhDXHQvhTYwHkOhtsRxRZxQhB7Y+bj8b3wRjBGCEOelIQiKDCy6FCRsh1zCVKxRQ7BzIlBcmKHiWHHgm+VMf8BkYd2tg8l1DiD/QXkXS 2vcLM2kLvKHfZkv4Wp35NAkFVdccNdWlt8E1lt6cSjigv8J/SeRBARYfPWXF/n29zczr658cvwE3vTJJrUQHmeP9Iy3m9mB7zthJ/M287/AdxppEv2qVN4AAAAAElFTkSuQmCC" />那么这是什么呢?这是Data URI scheme。
Java 图片处理 格式转换
Java 图片处理(包括 Jmagick 的应用) 图片处理( 的应用)作者: 佚名, 出处:IT 专家网,2010-10-29 08:30责任编辑: 谢妍妍,近期有使用到图片的压缩处理,由于在之前用 Java 处理时,在低像素的情况下, Java 处理的效果确实很差,然后尝试了用网上推荐的免费开源的第三方软件,利用 Java 的 jni 调用 dll 文件进行处理,效果还可以。
在此记录下,方便以后继续积累。
近期有使用到图片的压缩处理, 由于在之前用 Java 处理时, 在低像素的情况下, Java 处理的效果确实很差,然后尝试了用网上推荐的免费开源的第三方软件,利用 Java 的 jni 调用 dll 文件进行处理,效果还可以。
在此记录下,方便以后继续积累。
1、纯 Java 类处理图片代码Java 代码以下是代码片段: 以下是代码片段: /** * 转换图片大小,不变形 * * @param img * 图片文件 * @param width * 图片宽 * @param height * 图片高 */ public static void changeImge(File img, int width, int height) { try { Image image = ImageIO.read(img); //图片尺寸的大小处理, 如果长宽都小于规定大小, 则返回, 如果有一个大于规定大小, 则等比例缩放 int srcH = image.getHeight(null); int srcW = image.getWidth(null); if (srcH <= height && srcW <= width) { return;} int tmpH = width; int tmpW = height; //在长度和宽度都做了限制,不能超过设定值 while (srcH > height || srcW > width) { if(srcW > width) { tmpH = srcH * width / srcW; srcH = tmpH; srcW=width; } if(srcH > height) { tmpW = srcW * height / srcH; srcW = tmpW; srcH=height; } } BufferedImage bufferedImage = new BufferedImage(srcW, srcH, BufferedImage.TYPE_3BYTE_BGR); bufferedImage.getGraphics().drawImage( image.getScaledInstance(srcW, srcH, Image.SCALE_SMOOTH), 0, 0, srcW, srcH, null); FileOutputStream fos = new FileOutputStream(img); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos); encoder.encode(bufferedImage); fos.close(); // System.out.println("转换成功..."); } catch (IOException e) { e.printStackTrace(); throw new IllegalStateException("图片转换出错!", e); } }2、使用 Jmagick 辅助Html 代码(1)使用的 windows 下的 jmagick-win-6.3.9-q16.zip 地址是: /6.3.9/(2)doc 对应的 api 地址:/jmagick-doc/(3)安装 imagemagick,官方网站:/我使用的是:imagemagick-6.4.6-4-q16-windows-dll.exe :点击下载(4) 安装 imagemagick-6.4.6-4-q16-windows-dll.exe,将 安装目录下(按自己所 安装的目录找) 下的所有 dll 文件 copy 到系统盘下的 “c:\windows\system32\”文件 夹里(5) 配置环境变量再环境变量 path 里添加新的值 “c:\program files\imagemagick-6.4.6-4-q16“使 用 ide 可以不用配置(6)解压 jmagick-win-6.3.9-q16.zip将 jmagick.dll 复制到系统盘下的 “c:\windows\system32\”文件夹里 和 复制到 jdk 的 bin(例“d:\jdk6\bin”)文件里各一份将 jmagick.jar 复制到 tomcat 下的 lib 文件夹里 和 所使用项目的 web-inf 下 lib 文件里 各一份(7)web 应用如果部署到 tomcat 下,那么最好在 catalina.bat 文件中改变如下设置set java_opts=%java_opts% -xms256m -xmx768m -xx:maxpermsize=128m – djava.util.logging.manager=org.apache.juli.classloaderlogmanager – djava.util.logging.config.file=”${catalina.base}\conf\logging.properties”避免 heap 溢出的问题,参数看你自己的机器而定。
使用JS对中文字符串进行utf-8的Base64编码
使⽤JS对中⽂字符串进⾏utf-8的Base64编码Code:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="/1999/xhtml"><head><title></title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style type="text/css"><!--body{margin:0px;padding:0px;}body,td{font-size:9pt;}--></style><script type="text/javascript"><!--var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";//将Ansi编码的字符串进⾏Base64编码function encode64(input) {var output = "";var chr1, chr2, chr3 = "";var enc1, enc2, enc3, enc4 = "";var i = 0;do {chr1 = input.charCodeAt(i++);chr2 = input.charCodeAt(i++);chr3 = input.charCodeAt(i++);enc1 = chr1 >> 2;enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);enc4 = chr3 & 63;if (isNaN(chr2)) {enc3 = enc4 = 64;} else if (isNaN(chr3)) {enc4 = 64;}output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)+ keyStr.charAt(enc3) + keyStr.charAt(enc4);chr1 = chr2 = chr3 = "";enc1 = enc2 = enc3 = enc4 = "";} while (i < input.length);return output;}//将Base64编码字符串转换成Ansi编码的字符串function decode64(input) {var output = "";var chr1, chr2, chr3 = "";var enc1, enc2, enc3, enc4 = "";var i = 0;if (input.length % 4 != 0) {return "";}var base64test = /[^A-Za-z0-9\+\/\=]/g;if (base64test.exec(input)) {return "";}do {enc1 = keyStr.indexOf(input.charAt(i++));enc2 = keyStr.indexOf(input.charAt(i++));enc3 = keyStr.indexOf(input.charAt(i++));enc4 = keyStr.indexOf(input.charAt(i++));enc4 = keyStr.indexOf(input.charAt(i++));chr1 = (enc1 << 2) | (enc2 >> 4);chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);chr3 = ((enc3 & 3) << 6) | enc4;output = output + String.fromCharCode(chr1);if (enc3 != 64) {output += String.fromCharCode(chr2);}if (enc4 != 64) {output += String.fromCharCode(chr3);}chr1 = chr2 = chr3 = "";enc1 = enc2 = enc3 = enc4 = "";} while (i < input.length);return output;}function utf16to8(str) {var out, i, len, c;out = "";len = str.length;for(i = 0; i < len; i++) {c = str.charCodeAt(i);if ((c >= 0x0001) && (c <= 0x007F)) {out += str.charAt(i);} else if (c > 0x07FF) {out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));} else {out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));}}return out;}function utf8to16(str) {var out, i, len, c;var char2, char3;out = "";len = str.length;i = 0;while(i < len) {c = str.charCodeAt(i++);switch(c >> 4) {case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: // 0xxxxxxxout += str.charAt(i-1);break;case 12: case 13:// 110x xxxx 10xx xxxxchar2 = str.charCodeAt(i++);out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); break;case 14:// 1110 xxxx 10xx xxxx 10xx xxxxchar2 = str.charCodeAt(i++);char3 = str.charCodeAt(i++);out += String.fromCharCode(((c & 0x0F) << 12) |((char2 & 0x3F) << 6) |((char3 & 0x3F) << 0));break;}}return out;}// 测试代码开始var de = encode64(utf16to8("select ⽤户名 from ⽤户")); document.writeln(de+"<br>");var ee = utf8to16(decode64(de))var ee = utf8to16(decode64(de)) document.writeln(ee);// 测试代码结束//--></script></head><body></body></html>。
Base64JAVA后台编码与JS前台解码(解决中文乱码问题)
Base64JAVA后台编码与JS前台解码(解决中⽂乱码问题)中⽂通过Java后台进⾏Base64编码后传到前台,通过JS进⾏Base64解码时会出现中⽂乱码的问题,被这个问题也是困扰了⼏天,使⽤jquery.base64.js只能转码⾮中⽂字符,经过搜集各种⽅案,最终找到适合⾃⼰的解决⽅案。
Java后台编码,这⾥⽤的是mons.codec.binary.Base64:[java]1. private String base64Encode(String str) throws Exception {2. if (str != null) {3. String os = System.getProperty("");4. if (os.toLowerCase().startsWith("windows")) {5. str = str.replaceAll("\\r\\n", "<br/>");6. } else if (os.toLowerCase().startsWith("linux")) {7. str = str.replaceAll("\\n", "<br/>");8. }9. return new String(Base64.encodeBase64(str.getBytes("GBK")));10. }11. return null;12. }前台JS进⾏Base64编码与解码:第⼀段代码主要处理中⽂字符转换:[javascript]1. //UnicodeAnsi.js⽂件2. //把Unicode转成Ansi和把Ansi转换成Unicode3. function UnicodeChr() {4. return '00A4,00A7,00A8,00B0,00B1,00B7,00D7,00E0,00E1,00E8,00E9,00EA,00EC,00ED,00F2,00F3,00F7,00F9,00FA,00FC,0101,0113,011B,012B,014D,016B,01CE,01D0,01D2,01D4,01D65. }6.7. function AnsicodeChr() {8. return 'A1E8,A1EC,A1A7,A1E3,A1C0,A1A4,A1C1,A8A4,A8A2,A8A8,A8A6,A8BA,A8AC,A8AA,A8B0,A8AE,A1C2,A8B4,A8B2,A8B9,A8A1,A8A5,A8A7,A8A9,A8AD,A8B1,A8A3,A8AB,A8AF,A89. }10.11. function UnicodeToAnsi(chrCode) {12. var chrHex = chrCode.toString(16);13. chrHex = "000" + chrHex.toUpperCase();14. chrHex = chrHex.substr(chrHex.length - 4);15. var i = UnicodeChr().indexOf(chrHex);16. if (i != -1) {17. chrHex = AnsicodeChr().substr(i, 4);18. }19. return parseInt(chrHex, 16);20. }21.22. function AnsiToUnicode(chrCode) {23. var chrHex = chrCode.toString(16);24. chrHex = "000" + chrHex.toUpperCase();25. chrHex = chrHex.substr(chrHex.length - 4);26. var i = AnsicodeChr().indexOf(chrHex);27. if (i != -1) {28. chrHex = UnicodeChr().substr(i, 4);29. }30. return parseInt(chrHex, 16);31. }32.33. // 将Unicode编码的字符串,转换成Ansi编码的字符串34. function strUnicode2Ansi(asContents) {35. var len1 = asContents.length;36. var temp = "";37. for (var i = 0; i < len1; i++) {38. var varasc = asContents.charCodeAt(i);39. if (varasc < 0)40. varasc += 65536;41. if (varasc > 127)42. varasc = UnicodeToAnsi(varasc);43. if (varasc > 255) {44. var varlow = varasc & 65280;45. varlow = varlow >> 8;46. var varhigh = varasc & 255;47. temp += String.fromCharCode(varlow) + String.fromCharCode(varhigh);48. } else {49. temp += String.fromCharCode(varasc);50. }51. }52. return temp;53. }54.55. // 将Ansi编码的字符串,转换成Unicode编码的字符串56. function strAnsi2Unicode(asContents) {57. var len1 = asContents.length;58. var temp = "";59. var chrcode;60. for (var i = 0; i < len1; i++) {61. var varasc = asContents.charCodeAt(i);62. if (varasc > 127) {63. chrcode = AnsiToUnicode((varasc << 8) + asContents.charCodeAt(++i));64. } else {65. chrcode = varasc;66. }67. temp += String.fromCharCode(chrcode);68. }69. return temp;70. }第⼆段代码主要进⾏Base64编码与解码:[javascript]1. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";2. // 将Ansi编码的字符串进⾏Base64编码3. function encode64(input) {4. var output = "";5. var chr1, chr2, chr3 = "";6. var enc1, enc2, enc3, enc4 = "";7. var i = 0;8.9. do {10. chr1 = input.charCodeAt(i++);11. chr2 = input.charCodeAt(i++);12. chr3 = input.charCodeAt(i++);13.14. enc1 = chr1 >> 2;15. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);16. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);17. enc4 = chr3 & 63;18.19. if (isNaN(chr2)) {20. enc3 = enc4 = 64;21. } else if (isNaN(chr3)) {22. enc4 = 64;23. }24.25. output = output +26. keyStr.charAt(enc1) +27. keyStr.charAt(enc2) +28. keyStr.charAt(enc3) +29. keyStr.charAt(enc4);30. chr1 = chr2 = chr3 = "";31. enc1 = enc2 = enc3 = enc4 = "";32. } while (i < input.length);33.34. return output;35. }36.37. // 将Base64编码字符串转换成Ansi编码的字符串38. function decode64(input) {39. var output = "";40. var chr1, chr2, chr3 = "";41. var enc1, enc2, enc3, enc4 = "";42. var i = 0;43.44. if (input.length % 4 != 0) {45. return "";46. }47. var base64test = /[^A-Za-z0-9\+\/\=]/g;48. if (base64test.exec(input)) {49. return "";50. }51.52. do {53. enc1 = keyStr.indexOf(input.charAt(i++));54. enc2 = keyStr.indexOf(input.charAt(i++));55. enc3 = keyStr.indexOf(input.charAt(i++));56. enc4 = keyStr.indexOf(input.charAt(i++));57.58. chr1 = (enc1 << 2) | (enc2 >> 4);59. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);60. chr3 = ((enc3 & 3) << 6) | enc4;61.62. output = output + String.fromCharCode(chr1);63.64. if (enc3 != 64) {65. output += String.fromCharCode(chr2);66. }67. if (enc4 != 64) {68. output += String.fromCharCode(chr3);69. }70.71. chr1 = chr2 = chr3 = "";72. enc1 = enc2 = enc3 = enc4 = "";73.74. } while (i < input.length);75.76. return output;77. }将以上两段代码保存到两个js⽂件中,并引⼊到页⾯中就可以了。
java将图片转为base64返回给前端
java将图⽚转为base64返回给前端本⽂实例为⼤家分享了java将图⽚转为base64返回给前端的具体代码,供⼤家参考,具体内容如下⼀、controller端代码@RequestMapping(value = "/captcha")public void imagecode(HttpServletRequest request, HttpServletResponse response) throws Exception {JSONObject object = new JSONObject();CaptchaGenerator vcg = new CaptchaGenerator();String vcode = vcg.generatorVCode();BufferedImage vcodeImage = vcg.generatorVCodeImage(vcode, true);response.setDateHeader("Expires", 0);response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");response.addHeader("Cache-Control", "post-check=0, pre-check=0");response.setHeader("Pragma", "no-cache");ByteArrayOutputStream outputStream = new ByteArrayOutputStream();response.addHeader("code", vcode.toLowerCase());try {ImageIO.write(vcodeImage, "png", outputStream);BASE64Encoder encoder = new BASE64Encoder();String base64 = encoder.encodeBuffer(outputStream.toByteArray()).trim();base64 = base64.replaceAll("\n", "").replaceAll("\r", "");object.put("code", "data:image/jpg;base64," + base64);response.getWriter().write(object.toString());} catch (IOException e) {response.getWriter().write("");} finally {if (outputStream != null) {outputStream.flush();outputStream.close();response.getWriter().close();}}}⼆、⽣成验证码的代码(从某博客拷过来直接⽤的)package com.kinth.security.web.util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import java.util.Random;/*** 验证码⽣成器***/public class CaptchaGenerator {/*** 验证码来源*/final private char[] code = {'2', '3', '4', '5', '6', '7', '8', '9','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v','w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F','G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R','S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};/**"Verdana", "Times", "Tahoma", "Georgia"};/*** 字体样式*/final private int[] fontStyles = new int[]{Font.BOLD, Font.ITALIC|Font.BOLD};/*** 验证码长度* 默认4个字符*/private int vcodeLen = 4;/*** 验证码图⽚字体⼤⼩* 默认17*/private int fontsize = 21;/*** 验证码图⽚宽度*/private int width = (fontsize+1)*vcodeLen+10;/*** 验证码图⽚⾼度*/private int height = fontsize+12;/*** ⼲扰线条数* 默认3条*/private int disturbline = 3;public CaptchaGenerator(){}/*** 指定验证码长度* @param vcodeLen 验证码长度*/public CaptchaGenerator(int vcodeLen) {this.vcodeLen = vcodeLen;this.width = (fontsize+1)*vcodeLen+10;}/*** ⽣成验证码图⽚* @param vcode 要画的验证码* @param drawline 是否画⼲扰线* @return*/public BufferedImage generatorVCodeImage(String vcode, boolean drawline){//创建验证码图⽚BufferedImage vcodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = vcodeImage.getGraphics();//填充背景⾊g.setColor(new Color(246, 240, 250));g.fillRect(0, 0, width, height);if(drawline){drawDisturbLine(g);}//⽤于⽣成伪随机数Random ran = new Random();//在图⽚上画验证码for(int i = 0;i < vcode.length();i++){//设置字体g.setFont(new Font(fontNames[ran.nextInt(fontNames.length)], fontStyles[ran.nextInt(fontStyles.length)], fontsize)); //随机⽣成颜⾊g.setColor(getRandomColor());//画验证码g.drawString(vcode.charAt(i)+"", i*fontsize+10, fontsize+5);}//释放此图形的上下⽂以及它使⽤的所有系统资源* 获得旋转字体的验证码图⽚* @param vcode* @param drawline 是否画⼲扰线* @return*/public BufferedImage generatorRotateVCodeImage(String vcode, boolean drawline){//创建验证码图⽚BufferedImage rotateVcodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics2D g2d = rotateVcodeImage.createGraphics();//填充背景⾊g2d.setColor(new Color(246, 240, 250));g2d.fillRect(0, 0, width, height);if(drawline){drawDisturbLine(g2d);}//在图⽚上画验证码for(int i = 0;i < vcode.length();i++){BufferedImage rotateImage = getRotateImage(vcode.charAt(i));g2d.drawImage(rotateImage, null, (int) (this.height * 0.7) * i, 0);}g2d.dispose();return rotateVcodeImage;}/*** ⽣成验证码* @return 验证码*/public String generatorVCode(){int len = code.length;Random ran = new Random();StringBuffer sb = new StringBuffer();for(int i = 0;i < vcodeLen;i++){int index = ran.nextInt(len);sb.append(code[index]);}return sb.toString();}/*** 为验证码图⽚画⼀些⼲扰线* @param g*/private void drawDisturbLine(Graphics g){Random ran = new Random();for(int i = 0;i < disturbline;i++){int x1 = ran.nextInt(width);int y1 = ran.nextInt(height);int x2 = ran.nextInt(width);int y2 = ran.nextInt(height);g.setColor(getRandomColor());//画⼲扰线g.drawLine(x1, y1, x2, y2);}}/*** 获取⼀张旋转的图⽚* @param c 要画的字符* @return*/private BufferedImage getRotateImage(char c){BufferedImage rotateImage = new BufferedImage(height, height, BufferedImage.TYPE_INT_ARGB);Graphics2D g2d = rotateImage.createGraphics();//设置透明度为0g2d.setColor(new Color(255, 255, 255, 0));g2d.fillRect(0, 0, height, height);Random ran = new Random();g2d.setFont(new Font(fontNames[ran.nextInt(fontNames.length)], fontStyles[ran.nextInt(fontStyles.length)], fontsize)); g2d.setColor(getRandomColor());double theta = getTheta();//旋转图⽚g2d.rotate(theta, height/2, height/2);g2d.drawString(Character.toString(c), (height-fontsize)/2, fontsize+5);* @return 返回⼀个随机颜⾊*/private Color getRandomColor(){Random ran = new Random();return new Color(ran.nextInt(220), ran.nextInt(220), ran.nextInt(220)); }/*** @return ⾓度*/private double getTheta(){return ((int) (Math.random()*1000) % 2 == 0 ? -1 : 1)*Math.random(); }/*** @return 验证码字符个数*/public int getVcodeLen() {return vcodeLen;}/*** 设置验证码字符个数* @param vcodeLen*/public void setVcodeLen(int vcodeLen) {this.width = (fontsize+3)*vcodeLen+10;this.vcodeLen = vcodeLen;}/*** @return 字体⼤⼩*/public int getFontsize() {return fontsize;}/*** 设置字体⼤⼩* @param fontsize*/public void setFontsize(int fontsize) {this.width = (fontsize+3)*vcodeLen+10;this.height = fontsize+15;this.fontsize = fontsize;}/*** @return 图⽚宽度*/public int getWidth() {return width;}/*** 设置图⽚宽度* @param width*/public void setWidth(int width) {this.width = width;}/*** @return 图⽚⾼度*/public int getHeight() {return height;}/*** 设置图⽚⾼度* @param height*/public void setHeight(int height) {this.height = height;}/*** @return ⼲扰线条数*/* 设置⼲扰线条数* @param disturbline*/public void setDisturbline(int disturbline) {this.disturbline = disturbline;}}三、前端显⽰<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%><!DOCTYPE html><html><head><meta charset="ISO-8859-1"><title>Insert title here</title><script src="../static/model/js/jquery-1.11.2.min.js"></script></head><body><img id="randomImage" src="" /><script type="text/javascript">$(function() {refreshimg();})function refreshimg() {$.ajax({type : "POST",dataType : "json",url : "../article/captcha",success : function(data) {console.log('base64=' + data.codePic);$('#randomImage').attr('src', data.code);},error : function() {}});$("#randomImage").click(refreshimg)}</script></body></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
java将一个图片转换为字符串格式
java将⼀个图⽚转换为字符串格式package ylxControlServer.frame.util;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.File;import javax.imageio.ImageIO;import mons.logging.Log;import mons.logging.LogFactory;public class ImageToString {private static Log log = LogFactory.getLog(ImageToString.class);// 根据图⽚地址将图⽚转换为字符串类型的数据public String imageToString(String picture) {StringBuffer sb2 = new StringBuffer();BufferedImage image1 = getImage(picture);byte[] img = getBytes(image1);for (int i = 0; i < img.length; i++) {if (sb2.length() == 0) {sb2.append(img[i]);} else {sb2.append("," + img[i]);}}return sb2.toString();}// 将BufferImage 转换为字节数组private byte[] getBytes(BufferedImage image) {ByteArrayOutputStream baos = new ByteArrayOutputStream();try {ImageIO.write(image, "PNG", baos);} catch (Exception e) {(e);}return baos.toByteArray();}// 根据图⽚地址得到BufferedImagepublic static BufferedImage getImage(String picture) {try {BufferedImage bImage = ImageIO.read(new File(picture));return bImage;} catch (Exception ex) {(ex);return null;}}}(上⾯的类将⼀个图⽚转换为字符串)字符串的格式是:String a= "1,2,4,4,5,5,5,565";得到图⽚的字符串后,我们还得将字符串转换为图⽚:package ylxControlServer.frame.util;import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.File;import java.io.IOException;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import javax.imageio.ImageIO;public class StringToImage {public static String fileformat = "png";public static String fileNameFormat = "yyyy-MM-dd_HH-mm-ss";// 将字符串格式的图⽚转换为图⽚并保存public void stringToImage(String string, String saveDir) {if (string.contains(",")) {// 这⾥没有⾃带的那个分割⽅法,原因是分割速度没有这个快,有⼈考证在分割字符长度很⼤的情况下,系统的分割⽅法容易造成内存溢出。
java将类转换为字符串的方法
java将类转换为字符串的方法将类转换为字符串是在Java开发中经常会遇到的一个问题。
当我们需要将一个类的实例转换为字符串时,可以使用以下几种方法。
方法一:使用toString()方法Java中的每个类都继承了Object类,而Object类中有一个toString()方法,用于返回该对象的字符串表示。
我们可以重写这个方法,根据我们的需求来定义对象的字符串表示。
假设有一个Person类,包含name和age两个属性,重写toString()方法如下:```javapublic class Person {private String name;private int age;// 构造方法和其他方法省略@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}}```在上面的例子中,我们重写了toString()方法,将name和age属性拼接成一个字符串,并返回。
这样,当我们需要将Person类的实例转换为字符串时,就可以直接调用toString()方法了。
例如:```javaPerson person = new Person("张三", 20);String str = person.toString();System.out.println(str); // 输出:Person{name='张三', age=20}```方法二:使用String.valueOf()方法除了重写toString()方法,我们还可以使用String.valueOf()方法将一个对象转换为字符串。
这个方法有多个重载版本,可以接受不同类型的参数。
将图片转成base64字符串并在JSP页面显示的Java代码
*本事例主要讲了如下几点:* 1:将图片转换为BASE64加密字符串.* 2:将图片流转换为BASE64加密字符串.* 3:将BASE64加密字符串转换为图片.* 4:在jsp文件中以引用的方式和BASE64加密字符串方式展示图片. 首先看工具类:import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;import java.io.InputStream;import javax.imageio.ImageIO;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/*** @author IluckySi* @since 20150122*/public class ImageUtil {private static BASE64Encoder encoder = new sun.misc.BASE64Encoder();private static BASE64Decoder decoder = new sun.misc.BASE64Decoder();/*** 将图片转换为BASE64加密字符串.* @param imagePath 图片路径.* @param format 图片格式.* @return*/public String convertImageToByte(String imagePath, String format) { File file = new File(imagePath);BufferedImage bi = null;ByteArrayOutputStream baos = null;String result = null;try {bi = ImageIO.read(file);baos = new ByteArrayOutputStream();ImageIO.write(bi, format == null ? "jpg" : format, baos);byte[] bytes = baos.toByteArray();result = encoder.encodeBuffer(bytes).trim();System.out.println("将图片转换为BASE64加密字符串成功!");} catch (IOException e) {System.out.println("将图片转换为BASE64加密字符串失败: " + e); } finally {try {if(baos != null) {baos.close();baos = null;}} catch (Exception e) {System.out.println("关闭文件流发生异常: " + e);}return result;}/*** 将BASE64加密字符串转换为图片.* @param base64String* @param imagePath 图片生成路径.* @param format 图片格式.*/public void convertByteToImage(String base64String, String imagePath, String fo rmat) {byte[] bytes = null;ByteArrayInputStream bais = null;BufferedImage bi = null;File file = null;bytes = decoder.decodeBuffer(base64String);bais = new ByteArrayInputStream(bytes);bi = ImageIO.read(bais);file = new File(imagePath);ImageIO.write(bi, format == null ? "jpg" : format, file);System.out.println("将BASE64加密字符串转换为图片成功!");} catch (IOException e) {System.out.println("将BASE64加密字符串转换为图片失败: " + e); } finally {try {if(bais != null) {bais.close();bais = null;}} catch (Exception e) {System.out.println("关闭文件流发生异常: " + e);}}}}然后看测试类:import java.io.InputStream;import com.ilucky.util.image.ImageUtil;/*** 本事例主要讲了如下几点:* 1:将图片转换为BASE64加密字符串.* 2:将图片流转换为BASE64加密字符串.* 3:将BASE64加密字符串转换为图片.* 4:在jsp文件中以引用的方式和BASE64加密字符串方式展示图片. * @author IluckySi* @since 20150122*/public class MainTest {public static void main(String[] args) {ImageUtil imageUtil = new ImageUtil();String base64String = imageUtil.convertImageToByte("D:\\test.png", "png");System.out.println(base64String);imageUtil.convertByteToImage(base64String, "D:\\test2.png", "png");InputStream is = MainTest.class.getResourceAsStream("test.png");String base64String2 = imageUtil.convertImageStreamToByte(is, "png");System.out.println(base64String2);imageUtil.convertByteToImage(base64String2, "D:\\test3.png", "png");}}最后看jsp文件:<!DOCTYPE html><html><head><title>index.html</title><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="this is my page"><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><!--data表示取得数据的协定名称,image/png是数据类型名称,base64 是数据的编码方法,逗号后面是image/png文件base64编码后的数据.data:text/css;base64,base64编码的CSS代码data:text/javascript,Javascript代码data:text/javascript;base64,base64编码的Javascript代码data:image/gif;base64,base64编码的gif图片数据data:image/png;base64,base64编码的png图片数据data:image/jpeg;base64,base64编码的jpeg图片数据data:image/x-icon;base64,base64编码的icon图片数据--><img src="test.png"/><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAAB zenr0AAAFYklEQVR42sVXfUyUdRz/8XKhMZQO7nmeuwMFwrBEVJqgDOcUHZvNuTarrdKam0zdKrckAy4goowxbaM5 hE1yjVV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QscNkRsv351WbExhoBDXT5zN+4XMcfNVYMv2dTYM0eZ4H0zGAWMz0L9JaK1P 1PRQ7EWa0Bn3aJdh2NL2vAEQ2u2jGwZo+zQHq7zJBZrusyc9IZEOEX8sM/yFxokafI8LO9jrx1GgaqY+CujY Hr0BhYs5eXoynO9KffADOc+eEfyUyT19Owp0SsKd0U5eYrlU+xvMaLk3S0OcxAbTRcB73BH mdpSWNcn5dPejNDZq2d8jiWG4W07Q39JCctVr3T+br2ZY+bcac6CoPvzoGryhvscUaOr88CPenNDGb 5fCPqKha2o3kRF1MTKfA++uxHNNx4IwrDVZFwveMbnJFD7uSzQC960psZft8Je4rFkzXPzh5eME+ HTTfUs94mbxx1W+cCVbMwuH82XNOAM3LIpUZppQe96EnvoN6K5TXaVfPMbCxO1BAVbeCJzBj8 9tYsDO+/DwOVEX5BDrmbpYZaetCLnkG/ll8qEqK7WOQe32lybs54AKd23I/RA+EYqDAFBXJPSg219K AXPWf8y+iKQxhXHaLyRklI363yUAzsC8OghGtfqE9wRg651FBLj7v/aTb+ul4oUi4VipIuh+i+WSKG+ spC8Gd5CPr/BWv2OJOcHsl9XWoW/v/fht5LhLUXiARZb71cJOquFIlv5BH2EqzZ40xyEsm9OJM fp/cS/wC6xRqbyM2GFQAAAABJRU5ErkJggg=="/></body></html>部署项目,启动服务器,访问jsp页面,会看到浏览器上有两张一样的图片.。
java实现图片合成,并添加文字
java实现图⽚合成,并添加⽂字最近公司⼀个需要,需要把商品的优惠卷分享链接,⽣成⼀个⼆维码然后和商品主图合成⼀张,并且在新合成的主图增加商品信息的描述,好了直接看合成后图⽚的样式下⾯我就直接贴代码,⾸先是Contorller层/*** 淘宝⼆维码,商品主图,合成⼀张图** @param pictUrl* @param request* @param response* @throws IOException*/@RequestMapping("/getTaoBaoqQRCode")public void getTaoBaoqQRCode(TaoBaoQRCode taoBaoQRCode, HttpServletRequest request,HttpServletResponse response) throws IOException {ServletOutputStream os = null;InputStream buffin = null;try {// ⼆维码String couponUlr = "https:" + taoBaoQRCode.getCouponShareUrl();// ⾼额卷分享链接byte[] imgByte = QrCodeUtil.createQrCode2Bytes(250, 250, couponUlr);buffin = new ByteArrayInputStream(imgByte);BufferedImage couponImage = ImageIO.read(buffin);// 商品主图String imageUrl = "https:" + taoBaoQRCode.getPictUrl();URL url = new URL(imageUrl);BufferedImage picImage = ImageIO.read(url);BufferedImage modifyImage =imageHandleUtil.mergeImage(picImage, couponImage, taoBaoQRCode.getTitle(),taoBaoQRCode.getReservePrice(), taoBaoQRCode.getZkFinalPrice());response.setContentType("image/jpg");os = response.getOutputStream();ImageIO.write(modifyImage, "jpg", os);os.flush();} catch (Exception e) {LOGGER.error("getTaoBaoqQRCode error");e.printStackTrace();} finally {buffin.close();os.close();}}⼆维码QrCodeUtil ⽣成帮助类public class QrCodeUtil {private static final int DAFAULT_WIDTH = 360;private static final int DAFAULT_HEIGHT = 360;private static final Logger LOGGER = LoggerFactory.getLogger(QrCodeUtil.class);public static String createQrCode(String text) {return createQrCode(DAFAULT_WIDTH, DAFAULT_HEIGHT, text);}public static String createQrCode(int widht, int height, String text) {HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");try {byte[] bytes = createQrCode2Bytes(widht, height, text);String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";return UpYunClient.upload(fileName, bytes);} catch (Exception e) {LOGGER.error("create qrcode error", e);}return null;}public static byte[] createQrCode2Bytes(String text) {return createQrCode2Bytes(DAFAULT_WIDTH, DAFAULT_HEIGHT, text);}public static byte[] createQrCode2Bytes(int widht, int height, String text) {HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");try {BitMatrix bitMatrix =new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, widht, height,hints);ByteArrayOutputStream out = new ByteArrayOutputStream();BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);ImageIO.write(image, "png", out);return out.toByteArray();} catch (Exception e) {LOGGER.error("create qrcode error", e);}return null;}/*** ⽣成条形码并已字节码形式返回,⽣成的图⽚格式为png** @param contents* @param width* @param height* @return*/public static byte[] createBarcode2Byte(String contents, int width, int height) {int codeWidth = 3 + // start guard(7 * 6) + // left bars5 + // middle guard(7 * 6) + // right bars3; // end guardcodeWidth = Math.max(codeWidth, width);try {BitMatrix bitMatrix =new MultiFormatWriter().encode(contents, BarcodeFormat.CODE_128, codeWidth, height, null);BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);ByteArrayOutputStream out = new ByteArrayOutputStream();ImageIO.write(image, "png", out);return out.toByteArray();} catch (Exception e) {e.printStackTrace();}return null;}}⼆维码⽣成我这⾥⽤的是⾕歌的看下⾯maven pom.xml ⽂件<!-- 条形码、⼆维码⽣成 --><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>2.2</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>2.2</version></dependency>合成图⽚⽅法如何package mon.util;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import .URL;import javax.imageio.ImageIO;import ponent;@Componentpublic class ImageHandleUtil {private Font font = null;private Graphics2D g = null;/*** 导⼊本地图⽚到缓冲区** @param imgName* @return*/public BufferedImage loadImageLocal(String imgName) {try {return ImageIO.read(new File(imgName));} catch (IOException e) {e.printStackTrace();}return null;}/*** 导⼊⽹络图⽚到缓冲区** @param imgName* @return*/public BufferedImage loadImageUrl(String imgName) {try {URL url = new URL(imgName);return ImageIO.read(url);} catch (IOException e) {e.printStackTrace();}return null;}/*** ⽣成新图⽚到本地** @param newImage* @param img*/public void writeImageLocal(String newImage, BufferedImage img) {if (newImage != null && img != null) {try {// ⽬录不存在则创建String dirUrl = newImage.substring(0, stIndexOf(File.separator)); File dir = new File(dirUrl);if (!dir.exists()) {dir.mkdirs();}File outputfile = new File(newImage);ImageIO.write(img, "png", outputfile);} catch (IOException e) {e.printStackTrace();}}}/*** 设定⽂字的字体等** @param fontStyle* @param fontSize*/public void setFont(String name, int style, int fontSize) {this.font = new Font(name, style, fontSize);}/*** 修改图⽚,返回修改后的图⽚缓冲区(只输出⼀⾏⽂本),图⽚居中显⽰** @param img* @param content* @param y* @param color* @return*/public BufferedImage modifyImage(BufferedImage img, Object content, int y, Color color) {try {g = img.createGraphics();g.setBackground(Color.WHITE);g.setColor(color);// 设置字体颜⾊g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 抗锯齿 if (this.font != null)g.setFont(this.font);int width = img.getWidth();// 图⽚宽度if (content != null) {String str = content.toString();int strWidth = g.getFontMetrics().stringWidth(str);// 字体宽度g.drawString(str, (width - strWidth) / 2, y);}g.dispose();} catch (Exception e) {e.printStackTrace();}return img;}public BufferedImage modifyImage(BufferedImage img, Object content, int x, int y, Color color) {try {g = img.createGraphics();g.setBackground(Color.WHITE);g.setColor(color);// 设置字体颜⾊g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);// 抗锯齿 if (this.font != null)g.setFont(this.font);if (content != null) {String str = content.toString();g.drawString(str, x, y);}g.dispose();} catch (Exception e) {e.printStackTrace();}return img;}/*** 将⼀张图⽚画在另⼀张图⽚上** @param addImage 被添加的图⽚* @param sourceImg 源图* @param x* @param y* @param width* @param height* @return*/public BufferedImage modifyImagetogeter(BufferedImage addImage, BufferedImage sourceImg, int x,int y) {int width = addImage.getWidth();int height = addImage.getHeight();try {g = sourceImg.createGraphics();g.drawImage(addImage, x, y, width, height, null);g.dispose();} catch (Exception e) {e.printStackTrace();}return sourceImg;}/**** @param img1* @param img2* @param title 标题* @param reservePrice 现价* @param zkFinalPrice 折扣价* @return BufferedImage* @throws IOException*/public BufferedImage mergeImage(BufferedImage img1, BufferedImage img2,String title,String reservePrice,String zkFinalPrice)throws IOException {Font font = new Font("微软雅⿊", Font.BOLD, 20);int w1 = img1.getWidth();int h1 = img1.getHeight();int w2 = img2.getWidth();int h2 = img2.getHeight();BufferedImage newImage = new BufferedImage(w1, h2 + h1 + h2/2, BufferedImage.TYPE_INT_RGB);// 新的图Graphics2D graphics = (Graphics2D) newImage.getGraphics();graphics.setBackground(Color.WHITE);graphics.fillRect(0, 0, newImage.getWidth(), newImage.getHeight());graphics.drawImage(img1, 0, 0, null);graphics.drawImage(img2, (newImage.getWidth()) / 2 - (w2 / 2), newImage.getHeight() - h2,null);graphics.setFont(font);graphics.setColor(Color.BLACK);int width = graphics.getFontMetrics(font).stringWidth(title);int startY = h1 + 30;if (width > newImage.getWidth()) {char[] array = title.toCharArray();StringBuilder sb = new StringBuilder(array[0]);for (char c : array) {sb.append(c);int newWidth = graphics.getFontMetrics(font).stringWidth(sb.toString());if ((newWidth + 19) >= newImage.getWidth()) {// 准备换⾏graphics.drawString(sb.toString(), 0, startY);startY += 30;sb.delete(0, sb.length());}}graphics.drawString(sb.toString(), 0, startY);} else {graphics.drawString(title, 0, startY);}graphics.drawString("现价¥"+reservePrice, 0, startY + 30);startY += 30;graphics.drawString("卷后价¥"+zkFinalPrice, 0, startY + 30);return newImage;}}两个帮助类⾥⾯有很多⽅法没⽤到,⼤家只要看⼏个关键的⽅法就可以了,TaoBaoQRCode 对象⾥⾯的属性我就没列出来了,⼤家⾃⼰根据⾃⼰的需求⽽定以上就是java 实现图⽚合成,并添加⽂字的详细内容,更多关于Java 图⽚合成的资料请关注其它相关⽂章!。
js把通过图片路径生成base64
js把通过图⽚路径⽣成base64主要思想: 使⽤canvas.toDataURL()⽅法将图⽚的绝对路径转换为base64编码.⼀、图⽚在本地服务器:var imgSrc = "img/1.jpg";//本地项⽬⽂件夹下的图⽚function getBase64(img){//传⼊图⽚路径,返回base64function getBase64Image(img,width,height) {var canvas = document.createElement("canvas");canvas.width = width ? width : img.width;canvas.height = height ? height : img.height;var ctx = canvas.getContext("2d");ctx.drawImage(img, 0, 0, canvas.width, canvas.height);var dataURL = canvas.toDataURL();return dataURL;}var image = new Image();image.src = img;var deferred=$.Deferred();if(img){image.onload =function (){deferred.resolve(getBase64Image(image));//将base64传给done上传处理}return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']}}getBase64(imgSrc).then(function(base64){console.log(base64);},function(err){console.log(err);});⼆、跨域<!DOCTYPE html><html><head><meta charset="UTF-8"><title>nick getBase64</title></head><body><div><img id="test" src="" alt=""/></div><script src="/libs/jquery/2.1.1/jquery.min.js"></script><script>var imgSrc = "https:///bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg";// var imgSrc = "img/1.jpg";function getBase64(img){//传⼊图⽚路径,返回base64function getBase64Image(img,width,height) {//width、height调⽤时传⼊具体像素值,控制⼤⼩ ,不传则默认图像⼤⼩var canvas = document.createElement("canvas");canvas.width = width ? width : img.width;canvas.height = height ? height : img.height;var ctx = canvas.getContext("2d");ctx.drawImage(img, 0, 0, canvas.width, canvas.height);var dataURL = canvas.toDataURL();return dataURL;}var image = new Image();image.crossOrigin = '';image.src = img;var deferred=$.Deferred();if(img){image.onload =function (){deferred.resolve(getBase64Image(image));//将base64传给done上传处理}return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest']}}getBase64(imgSrc).then(function(base64){console.log(base64);},function(err){console.log(err);});</script></body></html>最近做了⼀个项⽬⽤到了这个,html代码⽣成canvas然后⽣成图⽚。
Java图片与byte数组互相转换
Java图⽚与byte数组互相转换Java 图⽚与byte数组互相转换//图⽚到byte数组public byte[] image2byte(String path){byte[] data = null;FileImageInputStream input = null;try {input = new FileImageInputStream(new File(path));ByteArrayOutputStream output = new ByteArrayOutputStream();byte[] buf = new byte[1024];int numBytesRead = 0;while ((numBytesRead = input.read(buf)) != -1) {output.write(buf, 0, numBytesRead);}data = output.toByteArray();output.close();input.close();}catch (FileNotFoundException ex1) {ex1.printStackTrace();}catch (IOException ex1) {ex1.printStackTrace();}return data;}//byte数组到图⽚public void byte2image(byte[] data,String path){if(data.length<3||path.equals("")) return;try{FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));imageOutput.write(data, 0, data.length);imageOutput.close();System.out.println("Make Picture success,Please find image in " + path);} catch(Exception ex) {System.out.println("Exception: " + ex);ex.printStackTrace();}}//byte数组到16进制字符串public String byte2string(byte[] data){if(data==null||data.length<=1) return "0x";if(data.length>200000) return "0x";StringBuffer sb = new StringBuffer();int buf[] = new int[data.length];//byte数组转化成⼗进制for(int k=0;k<data.length;k++){buf[k] = data[k]<0?(data[k]+256):(data[k]);}//⼗进制转化成⼗六进制for(int k=0;k<buf.length;k++){if(buf[k]<16) sb.append("0"+Integer.toHexString(buf[k]));else sb.append(Integer.toHexString(buf[k]));}return "0x"+sb.toString().toUpperCase();}。
Java实现图片转base64字符串和图片互相转换
Java实现图⽚转base64字符串和图⽚互相转换⽬录Java实现图⽚转base64字符串和图⽚互相转换参考:base64编码字符串转换为图⽚,并写⼊⽂件/*** base64编码字符串转换为图⽚,并写⼊⽂件** @param imgStr base64编码字符串* @param path 图⽚路径* @return*/public static boolean base64StrToImage(String imgStr, String path) {if (imgStr == null)return false;BASE64Decoder decoder = new BASE64Decoder();try {// 解密byte[] b = decoder.decodeBuffer(imgStr);// 处理数据for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {b[i] += 256;}}//⽂件夹不存在则⾃动创建File tempFile = new File(path);if (!tempFile.getParentFile().exists()) {tempFile.getParentFile().mkdirs();}OutputStream out = new FileOutputStream(tempFile);out.write(b);out.flush();out.close();return true;} catch (Exception e) {return false;}}图⽚转base64字符串/*** 图⽚转base64字符串** @param imgFile 图⽚路径* @return*/public static String imageToBase64Str(String imgFile) {InputStream inputStream = null;byte[] data = null;try {inputStream = new FileInputStream(imgFile);data = new byte[inputStream.available()];inputStream.read(data);inputStream.close();} catch (IOException e) {e.printStackTrace();}// 加密BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);}测试:public static void main(String[] args) {String base64Str = imageToBase64Str("D:/pic/001.jpg");System.out.println(base64Str);boolean b = base64StrToImage(base64Str, "D:/pic/temp/002.jpg"); System.out.println(b);}。
前端把图片文件流转为base64格式展示在前端,显示图片
前端把图⽚⽂件流转为base64格式展⽰在前端,显⽰图⽚1、需求:前台需要展⽰图⽚,期望后台直接返回图⽚地址,但是后台给的是的⽂件流⽽不是⼀个图⽚地址,需要把⽂件流转为base64的格式展⽰出来2、在获取图⽚接⼝中需要添加responseType:"arraybuffer"添加responseType之后获取的数据如下图3、在需要的展⽰图⽚的位置添加⼀个img标签4、对src绑定的fileField变量进⾏赋值处理5、最终展⽰在前端页⾯的图⽚如下图所⽰6、所需代码// 图⽚接⼝export const getPicList = (params) => {return request({url: Vue.prototype.BASE_URL + '/examiner/showpic',method: 'get',params: { ...params },responseType: 'arraybuffer'})}//img标签<img class="imgWH" :src="fileField" alt />//请求图⽚接⼝并且对⽂件流进⾏处理let picParam = {filename: decodeURIComponent(row.bioinformaticsFilePath), };getPicList(picParam).then((res) => {var data = res.data;this.fileField ="data:image/png;base64," +btoa(new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte),""));});。
C#base64和图片互转
C#base64和图⽚互转C# imgage图⽚转base64字符/base64字符串转图⽚另存成//图⽚转为base64编码的字符串protected string ImgToBase64String(string Imagefilename){try{Bitmap bmp = new Bitmap(Imagefilename);MemoryStream ms = new MemoryStream();bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);byte[] arr = new byte[ms.Length];ms.Position = 0;ms.Read(arr, 0, (int)ms.Length);ms.Close();return Convert.ToBase64String(arr);}catch (Exception ex){return null;}}//base64编码的字符串转为图⽚protected Bitmap Base64StringToImage(string strbase64){try{byte[] arr = Convert.FromBase64String(strbase64);MemoryStream ms = new MemoryStream(arr);Bitmap bmp = new Bitmap(ms);bmp.Save(@"d:\test.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);//bmp.Save(@"d:\"test.bmp", ImageFormat.Bmp);//bmp.Save(@"d:\"test.gif", ImageFormat.Gif);//bmp.Save(@"d:\"test.png", ImageFormat.Png);ms.Close();return bmp;}catch (Exception ex){return null;}}2: 图⽚直接显⽰string Base64String = "";//太长就不贴出来了byte[] bytes = Convert.FromBase64String(Base64String);ImageTagId.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bytes);//3:转换成图⽚另存为然后图⽚显⽰出来public System.Drawing.Image Base64ToImage(string base64String){byte[] imageBytes = Convert.FromBase64String(base64String);MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);ms.Write(imageBytes, 0, imageBytes.Length);System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);return image;}使⽤⽅法:Base64ToImage(dd).Save(Server.MapPath("Hello.jpg"));Image1.ImageUrl = "Hello.jpg";4:直接转换存为路径下图⽚string dd = "";//base64字符串var bytes = Convert.FromBase64String(dd);using (var imageFile = new FileStream(@"d:\Hello1.jpg", FileMode.Create)){imageFile.Write(bytes, 0, bytes.Length);imageFile.Flush();}5://直接转换存为路径下图⽚string base64Str=""/byte[] bytes = System.Convert.FromBase64String(dd);File.WriteAllBytes(@"d:\newfile.jpg", bytes);string filePath = @"d:\MyImage.jpg";File.WriteAllBytes(filePath, Convert.FromBase64String(base64Str));6:多张base64图⽚转换为图⽚另存为public string Base64ToImage(string upimgPath, string base64String){string goodspath = Server.MapPath(upimgPath); //⽤来⽣成⽂件夹if (!Directory.Exists(goodspath)){Directory.CreateDirectory(goodspath);}var imgPath = string.Empty;if (!string.IsNullOrEmpty(base64String)){var splitBase = base64String.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);foreach (var item in splitBase){var path = upimgPath + Guid.NewGuid() + ".jpg";string filePath = Server.MapPath(path);// Server.MapPath(upimgPath + Guid.NewGuid() + ".jpg"); File.WriteAllBytes(filePath, Convert.FromBase64String(item));imgPath += path + ";";}}else { imgPath = ";"; }return imgPath.TrimEnd(';');}使⽤⽅法:va headimg="";Base64ToImage("UpLoadImg/HeadImage/", headimg)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
*本事例主要讲了如下几点: * 1:将图片转换为BASE64加密字符串. * 2:将图片流转换为BASE64加密字符串. * 3:将BASE64加密字符串转换为图片.* 4:在jsp文件中以引用的方式和BASE64加密字符串方式展示图片.首先看工具类:import ;import ;import ;import ;import ;import ;import ;import ;import ;/*** @author IluckySi1* @since*/public class ImageUtil {private static BASE64Encoder encoder = new ;private static BASE64Decoder decoder = new ;/*** 将图片转换为BASE64加密字符串.* @param imagePath 图片路径.* @param format 图片格式.* @return*/public String convertImageToByte(String imagePath, String format) { File file = new File(imagePath);BufferedImage bi = null;ByteArrayOutputStream baos = null;String result = null;try {bi = ImageIO.read(file);baos = new ByteArrayOutputStream();ImageIO.write(bi, format == null ? "jpg" : format, baos);byte[] bytes = baos.toByteArray();result = encoder.encodeBuffer(bytes).trim();"将图片转换为BASE64加密字符串成功!");} catch (IOException e) {"将图片转换为BASE64加密字符串失败: " + e);} finally {try {if(baos != null) {baos.close();baos = null;}} catch (Exception e) {"关闭文件流发生异常: " + e);}3}return result;}/*** 将BASE64加密字符串转换为图片.* @param base64String* @param imagePath 图片生成路径.* @param format 图片格式.*/public void convertByteToImage(String base64String, String imagePath, String fo rmat) {byte[] bytes = null;ByteArrayInputStream bais = null;BufferedImage bi = null;File file = null;try {bytes = decoder.decodeBuffer(base64String);bais = new ByteArrayInputStream(bytes);bi = ImageIO.read(bais);file = new File(imagePath);ImageIO.write(bi, format == null ? "jpg" : format, file);"将BASE64加密字符串转换为图片成功!");} catch (IOException e) {"将BASE64加密字符串转换为图片失败: " + e);} finally {try {if(bais != null) {bais.close();bais = null;}} catch (Exception e) {"关闭文件流发生异常: " + e);}}5}}然后看测试类:import ;import ;/*** 本事例主要讲了如下几点:* 1:将图片转换为BASE64加密字符串.* 2:将图片流转换为BASE64加密字符串.* 3:将BASE64加密字符串转换为图片.* 4:在jsp文件中以引用的方式和BASE64加密字符串方式展示图片. * @author IluckySi* @since*/public class MainTest {public static void main(String[] args) {ImageUtil imageUtil = new ImageUtil();String base64String = imageUtil.convertImageToByte("D:\\test.png", "png");;imageUtil.convertByteToImage(base64String, "D:\\test2.png", "png");InputStream is = "test.png");String base64String2 = imageUtil.convertImageStreamToByte(is, "png");;imageUtil.convertByteToImage(base64String2, "D:\\test3.png", "png");}}最后看jsp文件:<!DOCTYPE html><html><head><title>index.html</title>7<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="this is my page"><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body><!--data表示取得数据的协定名称,image/png是数据类型名称,base64 是数据的编码方法, 逗号后面是image/png文件base64编码后的数据.data:text/css;base64,base64编码的CSS代码data:text/javascript,Javascript代码data:text/javascript;base64,base64编码的Javascript代码data:image/gif;base64,base64编码的gif图片数据data:image/png;base64,base64编码的png图片数据data:image/jpeg;base64,base64编码的jpeg图片数据data:image/x-icon;base64,base64编码的icon图片数据--><img src="test.png"/><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAg CAYAAABzenr0AAAFYklEQVR42sVXfUyUdRz/8XKhMZQO7nmeuwMFwrBEVJqgDOcUHZvNuTarrdKam0zdKrckAy4goowxbaM5 hE1yjVVzLjLRokBFz2qsQPGFF8vmamtkL4s4OHDy6ff5EQcXx91hf/jHB777fj8v3+d57p7nOQFA3E uoPxcLhV90SlxziOSeUrHdWRz5fv1uc1fl03OGizdGgmBd/5K5mzNyyO0M4EkEXqBAiI58Ed9WE Fp1+MXYm1vW68hKM7AwJR5Wmx3RZqsCa/Y4I4dcaqilx10t0PGqCOssEjuvH7H9vW1zEgzNgK5ZYVh0 2HUN86w65tvGwJo9zhRHcqmhlh70mtEC7a8Ie2ep6dPfW5eM3OnbhMo9S6GbLV6h04Eccqmh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Kha2o3kRF1MTKfA+页眉内容+uxHNNx4IwrDVZFwveMbnJFD7uSzQC960psZft8Je4rFkzXPzh5eME+ HTTfUs94mbxx1W+cCVbMwuH82XNOAM3LIpUZppQe96EnvoN6K5TXaVfPMbCxO1BAVbeCJzBj8 9tYsDO+/DwOVEX5BDrmbpYZaetCLnkG/ll8qEqK7WOQe32lybs54AKd23I/RA+EYqDAFBXJPSg219K AXPWf8y+iKQxhXHaLyRklI363yUAzsC8OghGtfqE9wRg651FBLj7v/aTb+ul4oUi4VipIuh+i+WSKG+ spC8Gd5CPr/BWv2OJOcHsl9XWoW/v/fht5LhLUXiARZb71cJOquFIlv5BH2EqzZ40xyEsm9OJM fp/cS/wC6xRqbyM2GFQAAAABJRU5ErkJggg=="/></body></html>部署项目,启动服务器,访问jsp页面,会看到浏览器上有两张一样的图片.11。