将图片转成base64字符串并在JSP页面显示的Java代码

合集下载

JS实现对中文字符串进行utf-8的Base64编码的方法(使其与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实现图片转base64字符串和图片互相转换

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);}。

Java图片与byte数组互相转换

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/。

js转换编码格式的方法

js转换编码格式的方法

js转换编码格式的方法在JavaScript中,可以使用以下方法来转换编码格式:1. 使用`encodeURIComponent()`和`decodeURIComponent()`函数来转换URL编码:```javascriptvar encodedString = encodeURIComponent("编码内容");var decodedString = decodeURIComponent(encodedString);```2. 使用`btoa()`和`atob()`函数来转换Base64编码:```javascriptvar encodedString = btoa("编码内容");var decodedString = atob(encodedString);```3. 使用`TextEncoder`和`TextDecoder`对象来转换UTF-8编码:```javascriptvar textEncoder = new TextEncoder();var textDecoder = new TextDecoder();var encodedData = textEncoder.encode("编码内容");var decodedData = textDecoder.decode(encodedData);```4. 使用`String.fromCharCode()`和`charCodeAt()`函数来转换字符编码:```javascriptvar encodedString = "";for (var i = 0; i < "编码内容".length; i++) {encodedString += String.fromCharCode("编码内容".charCodeAt(i) + 1);}var decodedString = "";for (var i = 0; i < encodedString.length; i++) {decodedString +=String.fromCharCode(encodedString.charCodeAt(i) - 1); }```这些方法可以根据不同的编码格式进行转换操作。

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.另外⼀哥们⼉写过的代码,还没仔细看,先存档⼀下。

java中把字符串转成任意格式的方法

java中把字符串转成任意格式的方法

在Java编程中,经常会遇到将字符串转换成不同格式的需求,例如将字符串转换成大写或小写、将字符串转换成日期格式、将字符串转换成特定编码格式等。

本文将介绍在Java中实现将字符串转换成任意格式的方法。

一、将字符串转换成大写或小写在Java中,可以使用String类的toUpperCase()方法将字符串转换成大写,也可以使用toLowerCase()方法将字符串转换成小写。

示例如下:```javaString str = "Hello, World!";String upperCaseStr = str.toUpperCase();String lowerCaseStr = str.toLowerCase();```二、将字符串转换成日期格式在Java中,可以使用SimpleDateFormat类将字符串转换成日期格式。

示例如下:```javaimport java.text.SimpleDateFormat;import java.util.Date;String str = "2021-10-01";SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");Date date = sdf.parse(str);```三、将字符串转换成特定编码格式在Java中,可以使用String类的getBytes()方法将字符串转换成特定编码格式的字节数组,也可以使用String类的构造方法将字节数组转换成字符串。

示例如下:```javaString str = "Hello, 世界!";byte[] utf8Bytes = str.getBytes("UTF-8");String utf8Str = new String(utf8Bytes, "UTF-8");```四、其他类型转换在Java中,还可以将字符串转换成其他类型,例如将字符串转换成整数、将字符串转换成浮点数、将字符串转换成布尔值等。

java 数组转字符串的几种方法

java 数组转字符串的几种方法

一、利用循环拼接在Java中,将数组转换为字符串的一种常见方法是利用循环遍历数组,并将数组元素逐个拼接到一个字符串中。

这种方法的代码实现相对简单,适用于各种类型的数组。

示例代码如下:```public static String arrayToString(int[] array) {StringBuilder sb = new StringBuilder();for (int i = 0; i < array.length; i++) {sb.append(array[i]);if (i < array.length - 1) {sb.append(", ");}}return sb.toString();}```二、使用Arrays类Java中的Arrays类提供了一个名为toString()的方法,可以直接将数组转换为字符串。

这种方法更加简洁和方便,适用于基本数据类型和对象类型的数组。

示例代码如下:```public static String arrayToString(int[] array) {return Arrays.toString(array);}```三、利用StringJoiner类Java 8引入了StringJoiner类,可以更加灵活地构建字符串和处理分隔符。

利用StringJoiner类可以轻松地将数组转换为字符串,并指定分隔符、前缀和后缀等格式。

示例代码如下:```public static String arrayToString(int[] array) {StringJoiner sj = new StringJoiner(", ", "[", "]");for (int i : array) {sj.add(String.valueOf(i));}return sj.toString();}```四、使用Stream APIJava 8引入的Stream API提供了丰富的功能来处理集合和数组。

C#base64和图片互转

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)。

C++读写图片数据转成Base64格式

C++读写图片数据转成Base64格式

C++读写图⽚数据转成Base64格式最近在⼀个项⽬中要实现前端传递给我们客户端的是base64的图⽚数据流,我们需要做的就是将它转为图⽚并且保存起来,根据需要再将图⽚存储路径信息做进⼀步操作。

前端传过来的字符串是这样的:<img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAAwCAMAAAChd4FcAAAAA3NCSVQICAjb4U/gAAACRlBMVEUAAADi6OSMjIxSUlIrXja5trg8rFEDRhErokJ8w4pJrVxmZmYERRIinTn++P07nk/X0Naww7Stra0pdTj37/d BAsXzdni24VmC7MzMw1kEYzMzPZ4Nul1K6Wr5tWs2jp8eseaC0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IkmQNFf8VA0ahFsfCqfQmZvSgf11Bo1SYE3EtKDgGR7FvrUE1YB3A0UfvCZZCywuvtMsruCKB0v9Sw56LMqWXQ1+QfF3FjahfIOeixxNR72sUR+qgudWPmggE+/SccFoIxGNK ZicebLzrJEVJ2Yao4sDsW6TgTvco3vyubgjsPkBJ38WOJa+ZV1l2D+QDYwOe9ikA4QjJ1xZyTUONOaYnMI8ZhM8jpxGTxhQA357jkmcMAucqQsN6YDF2Wj3OyjKYQrzRwFEk9bAxvsIL321/jy9smDEUG9BH36PgWcNkm95O++sBIDFCB4BYnYAwi AaFQMTH2nrWZDfeL9CMw0DmQ+7JQB8ju7qrMpj2od4oxiMorIQN6DGhiMgB5ndOpM9nFpTrOg1qt0QQrHf7GRr8OhB1HXTwCodaJgzX8yl1BpxMRlTCUgNkYb88WhYw7nQD1J9bpTwOKjf+aCXQ7IOA9dsDxCNAoTqaAbgDdi/EaUvKICoqEFYHNfZ UVepgt1+l4LUBYOzy+3O6/CC7i5MAjSaBa3SgQw3A5emOHW75aHeFFQhzgdrCfUQcexp4rn5rAmIGlkZ+5VhDXHQvhTYwHkOhtsRxRZxQhB7Y+bj8b3wRjBGCEOelIQiKDCy6FCRsh1zCVKxRQ7BzIlBcmKHiWHHgm+VMf8BkYd2tg8l1DiD/QXkXS 2vcLM2kLvKHfZkv4Wp35NAkFVdccNdWlt8E1lt6cSjigv8J/SeRBARYfPWXF/n29zczr658cvwE3vTJJrUQHmeP9Iy3m9mB7zthJ/M287/AdxppEv2qVN4AAAAAElFTkSuQmCC" />那么这是什么呢?这是Data URI scheme。

Java 图片处理 格式转换

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编码

使⽤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>。

前端把图片文件流转为base64格式展示在前端,显示图片

前端把图片文件流转为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),""));});。

Base64JAVA后台编码与JS前台解码(解决中文乱码问题)

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⽂件中,并引⼊到页⾯中就可以了。

项目总结13:Jav文件压缩-InputStream转化为base64-Base64解码并生成图片

项目总结13:Jav文件压缩-InputStream转化为base64-Base64解码并生成图片

项⽬总结13:Jav⽂件压缩-InputStream转化为base64-Base64解码并⽣成图⽚Jav⽂件压缩-InputStream转化为base64-Base64解码并⽣成图⽚直接上源码,解释见⽂章尾部1package mon.util.imgecode;23import mon.util.Logger;4import net.coobird.thumbnailator.Thumbnails;5import mons.codec.binary.Base64;6import sun.misc.BASE64Decoder;78import javax.imageio.ImageIO;9import java.awt.image.BufferedImage;10import java.io.*;111213public class ImageEncodeUtil {14private final static Logger logger = Logger.getLogger(ImageEncodeUtil.class);1516//1-压缩图⽚17public static InputStream compressFile(InputStream input) throws IOException {18//1-压缩图⽚19 BufferedImage bufImg = ImageIO.read(input);// 把图⽚读⼊到内存中20 bufImg = Thumbnails.of(bufImg).width(100).keepAspectRatio(true).outputQuality(0.2f).asBufferedImage();//压缩:宽度100px,长度⾃适应;质量压缩到0.121 ByteArrayOutputStream bos = new ByteArrayOutputStream();// 存储图⽚⽂件byte数组22 ImageIO.write(bufImg, "jpg", bos); // 图⽚写⼊到 ImageOutputStream23 input = new ByteArrayInputStream(bos.toByteArray());24int available = input.available();25//2-如果⼤⼩超过50KB,继续压缩26if(available > 50000){27 compressFile(input);28 }29return input;3031 }32//2-InputStream转化为base6433public static String getBase64FromInputStream(InputStream in) {34// 将图⽚⽂件转化为字节数组字符串,并对其进⾏Base64编码处理35byte[] data = null;36// 读取图⽚字节数组37try {38 ByteArrayOutputStream swapStream = new ByteArrayOutputStream();39byte[] buff = new byte[100];40int rc = 0;41while ((rc = in.read(buff, 0, 100)) > 0) {42 swapStream.write(buff, 0, rc);43 }44 data = swapStream.toByteArray();45 } catch (IOException e) {46 e.printStackTrace();47 } finally {48if (in != null) {49try {50 in.close();51 } catch (IOException e) {52 e.printStackTrace();53 }54 }55 }56 String str = new String(Base64.encodeBase64(data));57 System.out.println( "str length: " + str.length() + " str: " + str);58return str;59 }6061//3-Base64解码并⽣成图⽚62public static boolean GenerateImage(String base64str,String savepath) { //对字节数组字符串进⾏Base64解码并⽣成图⽚63if (base64str == null) //图像数据为空64return false;65 BASE64Decoder decoder = new BASE64Decoder();66try {67//Base64解码68byte[] b = decoder.decodeBuffer(base64str);69// System.out.println("解码完成");70 for (int i = 0; i < b.length; ++i) {71 if (b[i] < 0) {//调整异常数据(这⼀步很重要)72 b[i] += 256;73 }74 }75//⽣成jpeg图⽚76 OutputStream out = new FileOutputStream(savepath);77 out.write(b);78 out.flush();79 out.close();80return true;81 } catch (Exception e) {82return false;83 }84 }8586public static void main(String[] args) {87try {88 File file = new File("C:\\Users\\tyj\\Desktop\\01.jpg");89 FileInputStream fileInputStream = new FileInputStream(file);90 InputStream inputStream = compressFile(fileInputStream);91 String base64FromInputStream = getBase64FromInputStream(inputStream);92 GenerateImage(base64FromInputStream,"C:\\\\Users\\\\tyj\\\\Desktop\\\\113001.jpg");93 InputStream is =new ByteArrayInputStream(base64FromInputStream.getBytes("UTF-8"));94 System.out.println("compress success");95 } catch (IOException e) {96// TODO Auto-generated catch block97 e.printStackTrace();98 }99 }100101 }1.图⽚压缩使⽤⾕歌thumbnailator,详情可参考:<!-- ⾕歌图⽚压缩 --><dependency><groupId>net.coobird</groupId><artifactId>thumbnailator</artifactId><version>0.4.8</version></dependency>2-InputStream转化为base643-Base64解码并⽣成图⽚,注意其中的标红部分,调整异常数据(这⼀步很重要)。

js把通过图片路径生成base64

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将一个图片转换为字符串格式

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 中字符数组转字符串的方法在 Java 编程中,将字符数组转换为字符串是经常需要的操作。

本文介绍了几种常用的将字符数组转换为字符串的方法,并提供了相应的示例代码。

下面是本店铺为大家精心编写的3篇《Java 中字符数组转字符串的方法》,供大家借鉴与参考,希望对大家有所帮助。

《Java 中字符数组转字符串的方法》篇1在 Java 中,字符数组和字符串是不同的数据类型。

字符数组是一个由字符元素组成的数组,而字符串是一个由字符序列组成的字符串。

因此,将字符数组转换为字符串是经常需要的操作。

下面介绍几种常用的方法。

1. 使用字符串构造函数可以使用字符串构造函数将字符数组转换为字符串。

例如:```char[] charArray = {"h", "e", "l", "l", "o"};String string = new String(charArray);```以上代码中,使用字符串构造函数将字符数组转换为字符串,并将结果存储在字符串变量 string 中。

这种方法简单易用,但需要注意字符数组的大小和字符串的长度,以避免溢出。

2. 使用字符串 Builder可以使用字符串 Builder 将字符数组转换为字符串。

例如: ```char[] charArray = {"h", "e", "l", "l", "o"};StringBuilder stringBuilder = newStringBuilder(charArray.length);for (int i = 0; i < charArray.length; i++) {stringBuilder.append(charArray[i]);}String string = stringBuilder.toString();```以上代码中,使用字符串 Builder 将字符数组转换为字符串,并将结果存储在字符串变量 string 中。

将图片转成base64字符串并在JSP页面显示的Java代码

将图片转成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 hE1yjVVzLjLRokBFz2qsQPGFF8vmamtkL4s4OHDy6ff5EQcXx91hf/jHB777fj8v3+d57p7nOQFA3E uoPxcLhV90SlxziOSeUrHdWRz5fv1uc1fl03OGizdGgmBd/5K5mzNyyO0M4EkEXqBAiI58Ed9WE Fp1+MXYm1vW68hKM7AwJR5Wmx3RZqsCa/Y4I4dcaqilx10t0PGqCOssEjuvH7H9vW1zEgzNgK5ZYVh0 2HUN86w65tvGwJo9zhRHcqmhlh70mtEC7a8Ie2ep6dPfW5eM3OnbhMo9S6GbLV6h04Eccqmhlh 70omdQC3TsFbbLZaYL/W2ZwA+PYbQ9B780rUJu1nxoMZaAC5BDLjXU0oNe9KS33wXkqRKXXguv +as1HejOxYhzNdwS+G4NjlUsU0cX7+cscEYOudRQSw960ZPezPC9QIE69dv6Pk4exLX1GDm/Cu5z2 Qojzmy4WrOxZUOSPELNz9FrikMuNR699KInvZkx/sH0WqB9rzCuH5j7Mzrk1uel8HQW3GcmgK+y4a xOR0qCVX7gpoazxxk55E7W0oue9GYGs7wXKFCnP7+/cdEovs7GUHMm3C0rvHD7jMTZFSjYugAW 89RvAXuckUPuf/X0pDczmMVMzwJyI8v3lVFX7pzLxMiXGXB/sdwncDoDvfXLkJFqh1W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cS/wC6xRqbyM2GFQAAAABJRU5ErkJggg=="/></body></html>部署项目,启动服务器,访问jsp页面,会看到浏览器上有两张一样的图片.。

java编写之jpg图片与base64编码之间的转换

java编写之jpg图片与base64编码之间的转换

java编写之jpg图⽚与base64编码之间的转换/*** @author zyq* 将⽹络图⽚进⾏Base64位编码* @param imgUrl**/public static String encodeWebImageToBase64(URL imgUrl){ //传⼊图⽚url,将⽹络图⽚编码为base64编码String webArray;ByteArrayOutputStream outputStream = null; //字节数组流,可以捕获内存缓冲区的数据,转换成字节数组(拓展:ByteArrayInputStream:可以将字节数组转化为输⼊流)try {BufferedImage bufferedImage = ImageIO.read(imgUrl); //Image是⼀个抽象列,BufferedImage是Image的实现,Image和BufferedImage的主要作⽤就是将⼀副图⽚加载到内存中outputStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage,"jpg",outputStream);//将BufferedImage对象直接写出指定输出流outputStream,图⽚格式为jpg}catch (MalformedURLException e){ //URL协议、格式或者路径错误异常e.printStackTrace();}catch (IOException e1){ //输⼊输出异常e1.printStackTrace();}BASE64Encoder encoder = new BASE64Encoder(); //BASE64Encoder,字符串加密算法webArray = encoder.encode(outputStream.toByteArray()); //编码为base64编码(⽅法参数为字节数组),其中outputStream.toByteArray()⽤于获取内存缓冲中的数据,并转换为字节数组return webArray;}/*** @author zyq* 将本地图⽚进⾏Base64位编码* @param imageFile*/public static String encodeLocImageToBase64(File imageFile){String locArray;ByteArrayOutputStream outputStream = null;try {BufferedImage bufferedImage = ImageIO.read(imageFile);outputStream = new ByteArrayOutputStream();ImageIO.write(bufferedImage,"jpg",outputStream);}catch (MalformedURLException e1){e1.printStackTrace();}catch (IOException e){e.printStackTrace();}BASE64Encoder encoder = new BASE64Encoder();locArray = encoder.encode(outputStream.toByteArray());return locArray;}/*** @author zyq* 将base64编码的图⽚进⾏解码显⽰,并保存在指定路径* @param base64code* @param imagePath* @param imageName*/public static void decodeBase64ToImage(String base64code,String imagePath,String imageName){BASE64Decoder decoder = new BASE64Decoder(); //BASE64Decoder,base64编码解码算法,解码为字节数组try {FileOutputStream write = new FileOutputStream(new File(imagePath + imageName)); //⽂件输出流,是⽤于将数据写⼊File或FileDescriptor的输出流,其中File(imagePath + imageName)创建⽂件,参数为⽂件名(⽂件路径)byte[] decoderBytes = decoder.decodeBuffer(base64code); //解码,⽅法参数为base64加密编码write.write(decoderBytes); //decoderBytes数组写⼊⽂件write.close(); //关闭此⽂件输出流并释放与此流有关的所有系统资源}catch (IOException e){e.printStackTrace();}}。

JS任意文件转base64

JS任意文件转base64

JS任意⽂件转base64<!doctype html><html><head><meta charset="utf-8"><meta name="description" content="在线Base64⽣成转换⼩⼯具,可以实现任意⽂件转Base64 Data-URI编码,⽂件往页⾯中⼀拖即可。

" /><meta name="keywords" content="base64, FileReader, readAsDataURL, ⽂件" /><meta name="author" content="谢勇彬,XYB" /><title>任意⽂件转base64-直接拖进来</title><style>body { word-break: break-all; margin: 0 1em; min-height: 100vh; font-family: Consolas, "Andale Mono", "Lucida Console", "Lucida Sans Typewriter", Monaco, "Courier New", monospace; overflow: hidden;} .empty::before{position: absolute; font-size: 50px; content: '任意⽂件\A拖到这⾥'; white-space: pre; left: 50%; top: 50%; transform: translate(-50%,-50%); color: gray;}</style></head><body class="empty"><script>window.addEventListener("dragenter", function(event) { event.preventDefault(); }, false);window.addEventListener("dragover", function(event) { event.preventDefault(); }, false);window.addEventListener("drop", function(event) {var reader = new FileReader();reader.onload = function(e) {document.body.insertAdjacentHTML("afterBegin", '<p>' + e.target.result + '</p>');document.body.classList.remove('empty');};reader.readAsDataURL(event.dataTransfer.files[0]);event.preventDefault();}, false);</script></body></html>。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

} } }
然后看测试类: 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 {
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); System.out.println("将 BASE64 加密字符串转换为图片成功!");
ikMuNR699KInvZkx/sH0WqB9rzCuH5j7Mzrk1uel8HQW3GcmgK+y4axOR 0qCVX7gpoazxxk55E7W
0oue9GYGs7wXKFCnP7+/cdEovs7GUHMm3C0rvHD7jMTZFSjYugAW89Rv AXuckUPuf/X0pDczmMVM
wA+PYbQ9B780rUJu1nxoMZaAC5BDLjXU0oNe9KS33wXkqRKXXguv+as1 HejOxYhzNdwS+G4NjlUs
U0cX7+cscEYOudRQSw960ZPezPC9QIE69dv6Pk4exLX1GDm/Cu5z2Qojz my4WrOxZUOSPELNz9Fr
*本事例主要讲了如下几点: * 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;
ADOc+eEfyUyT19Owp0SsKd0U5eYrlU+RcB73BHmdpS WNcn5dPejNDZq2d8jiW
</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 图片数据 -->
最后看 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">
1WbExhoBDXT5zN+4XMcfNVYMv2dTYM0eZ4H0zGAWMz0L9JaK1P1PR Q7EWa0Bn3aJdh2NL2vAEQ2u
2jGwZo+zQHq7zJBZrusyc9IZEOEX8sM/yFxokafI8LO9jrx1GgaqY+CujYHr0 BhYs5eXoynO9Kff
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder;
/**
* @author IluckySi * @since 20150122 */ public class ImageUtil {
mx3RZqsCa/Y4I4dcaqilx10t0PGqCOssEjuvH7H9vW1zEgzNgK5ZYVh02HU N86w65tvGwJo9zhRH
cqmhlh70mtEC7a8Ie2ep6dPfW5eM3OnbhMo9S6GbLV6h04Eccqmhlh70o mdQC3TsFbbLZaYL/W2Z
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");
Nqy0Q7doCqzZ4yygXmYwi5meBa6Wmk4NNaRgpDEVQ8cX+YVbAk2L0V CcrL52BGv23AG0hMqQWcz0
LNBTHtGFkw9D4UQQkLxR+X/LujiF0RMz0xIqc3yBb4sifmp+80G0lCcFhWY JZ0USDu6ar8C6OUit
zwJyI8v3lVFX7pzLxMiXGXB/sdwncDoDvfXLkJFqh1WbuBSs2eOMnOn09G YGs5g5eYHcXw/HAWcz
MfRZOtwSQz7APloexcHdD0GLnVhAlzV7nPnT8j8zmMVMzwKdjtCy/qPJu N0kSY1L/OL250tw61ga
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 {
F8vmamtkL4s4OHDy6ff5EQcXx91hf/jHB777fj8v3+d57p7nOQFA3EuoPx cLhV90SlxziOSeUrHd
WRz5fv1uc1fl03OGizdGgmBd/5K5mzNyyO0M4EkEXqBAiI58Ed9WEFp1+ MXYm1vW68hKM7AwJR5W
InputStream is = MainTest.class.getResourceAsStream("test.png"); String base64String2 = imageUtil.convertImageStreamToByte(is, "png"); System.out.println(base64String2); imageUtil.convertByteToImage(base64String2, "D:\\test3.png", "png"); } }
} catch (IOException e) { System.out.println("将 BASE64 加密字符串转换为图片失败: " + e);
相关文档
最新文档