使用Base64轉換圖片
利用Base64實現二進制和圖片之間的轉換,具體代碼以下:java
- import java.awt.image.BufferedImage;
- import java.io.ByteArrayInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.IOException;
-
- import javax.imageio.ImageIO;
-
- import org.apache.tomcat.util.codec.binary.Base64;
-
- public class ImageBinary {
-
- public static void main(String[] args) {
- String fileName = "D://code//test.jpg";
- System.out.println(getImageBinary(fileName));
- saveImage(getImageBinary(fileName));
- }
-
-
- public static String getImageBinary(String fileName) {
- File f = new File(fileName);
- BufferedImage bi;
- try {
- bi = ImageIO.read(f);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ImageIO.write(bi, "jpg", baos);
- byte[] bytes = baos.toByteArray();
- return Base64.encodeBase64String(bytes);
-
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- public static void saveImage(String base64String) {
- try {
- byte[] bytes1 = Base64.decodeBase64(base64String);
- ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
- BufferedImage bi1 = ImageIO.read(bais);
- File w2 = new File("D://code//22.jpg");// 能夠是jpg,png,gif格式
- ImageIO.write(bi1, "jpg", w2);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
url獲取圖片字節流
若經過url訪問圖片並轉換爲二進制流,就不能按照上述方法。經過url獲取圖片涉及url、網絡狀態等各類狀況。在代碼中涉及兩種不一樣的方法:一個是經過url的形式,另外一個是直接訪問本地資源(即圖片路徑)。詳見如下代碼:git
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- public class ImageUtil {
-
-
- public static byte[] getImageFromNetByUrl(String strUrl) {
- try {
- URL url = new URL(strUrl);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- conn.setConnectTimeout(5 * 1000);
- InputStream inStream = conn.getInputStream();
- byte[] btImg = readInputStream(inStream);
- return btImg;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- public byte[] getImageFromLocalByUrl(String strUrl) {
- try {
- File imageFile = new File(strUrl);
- InputStream inStream = new FileInputStream(imageFile);
- byte[] btImg = readInputStream(inStream);
- return btImg;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
-
-
- private static byte[] readInputStream(InputStream inStream) throws IOException {
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[10240];
- int len = 0;
- while ((len = inStream.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- }
- inStream.close();
- return outStream.toByteArray();
-
- }
-
- public static void main(String[] args) {
- String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";
- byte[] b = getImageFromNetByUrl(url);
- System.out.println(b);
- }
- }
url獲取圖片字節流
本節介紹的方法能夠說是前兩種方法的結合體,可是在二者的基礎上有所優化,如對url的狀態作判斷,此方法僅供參考,可根據具體需求作相應調整。apache
- import java.awt.image.BufferedImage;
- import java.io.BufferedInputStream;
- import java.io.ByteArrayOutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
-
- import javax.imageio.ImageIO;
-
- import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
-
- public class ImageUtils {
-
-
- public static String getImageBinary(String imageUrl) {
- String data = null;
- try {
- int HttpResult = 0;
- URL url = new URL(imageUrl);
- URLConnection urlconn = url.openConnection();
- urlconn.connect();
- HttpURLConnection httpconn = (HttpURLConnection) urlconn;
- HttpResult = httpconn.getResponseCode();
- if (HttpResult != HttpURLConnection.HTTP_OK)
- System.out.print("failed");
- else {
- BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
- BufferedImage bm = ImageIO.read(bis);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- String type = imageUrl.substring(imageUrl.length() - 3);
- ImageIO.write(bm, type, bos);
- bos.flush();
- data = Base64.encode(bos.toByteArray());
- bos.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return data;
-
- }
-
- public static void main(String[] args) {
- String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";
- String result = getImageBinary(url);
- System.out.println(result);
- }
- }
url獲取圖片字節流
本方法實現了主要實現瞭如下幾個功能:tomcat
一、經過url將圖片轉換爲字節流(十六進制的形式),並實現字節流與圖片之間的相互轉換;服務器
二、將本地圖片轉換爲字節流(十六進制的形式),並實現字節流與圖片之間的相互轉換;網絡
- import java.awt.image.BufferedImage;
- import java.io.BufferedInputStream;
- import java.io.ByteArrayOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.RandomAccessFile;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
-
- import javax.imageio.ImageIO;
-
- public class Utils {
-
- public static String getImgeHexStringByUrl(String imageUrl) {
- String res = null;
- try {
- int HttpResult = 0;
- URL url = new URL(imageUrl);
- URLConnection urlconn = url.openConnection();
- urlconn.connect();
- HttpURLConnection httpconn = (HttpURLConnection) urlconn;
- HttpResult = httpconn.getResponseCode();
- if (HttpResult != HttpURLConnection.HTTP_OK)
- System.out.print("failed");
- else {
- BufferedInputStream bis = new BufferedInputStream(urlconn.getInputStream());
- BufferedImage bm = ImageIO.read(bis);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- String type = imageUrl.substring(imageUrl.length() - 3);
- ImageIO.write(bm, type, bos);
- bos.flush();
- byte[] data = bos.toByteArray();
- res = byte2hex(data);
- bos.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return res;
- }
-
-
- public static String getImgeHexStringByLocalUrl(String imageUrl) {
- String res = null;
-
- try {
- File imageFile = new File(imageUrl);
- InputStream inStream = new FileInputStream(imageFile);
- BufferedInputStream bis = new BufferedInputStream(inStream);
- BufferedImage bm = ImageIO.read(bis);
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- String type = imageUrl.substring(imageUrl.length() - 3);
- ImageIO.write(bm, type, bos);
- bos.flush();
- byte[] data = bos.toByteArray();
- res = byte2hex(data);
- bos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return res;
- }
-
-
- public static void saveImage(String data, String fileName, String type) {
-
- BufferedImage image = new BufferedImage(300, 300, BufferedImage.TYPE_BYTE_BINARY);
- ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
- try {
- ImageIO.write(image, type, byteOutputStream);
-
- byte[] bytes = hex2byte(data);
- RandomAccessFile file = new RandomAccessFile(fileName, "rw");
- file.write(bytes);
- file.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
-
- public static byte[] hex2byte(String s) {
- byte[] src = s.toLowerCase().getBytes();
- byte[] ret = new byte[src.length / 2];
- for (int i = 0; i < src.length; i += 2) {
- byte hi = src[i];
- byte low = src[i + 1];
- hi = (byte) ((hi >= 'a' && hi <= 'f') ? 0x0a + (hi - 'a') : hi - '0');
- low = (byte) ((low >= 'a' && low <= 'f') ? 0x0a + (low - 'a') : low - '0');
- ret[i / 2] = (byte) (hi << 4 | low);
- }
- return ret;
- }
-
-
- public static String byte2hex(byte[] b) {
- char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
- char[] out = new char[b.length * 2];
- for (int i = 0; i < b.length; i++) {
- byte c = b[i];
- out[i * 2] = Digit[(c >>> 4) & 0X0F];
- out[i * 2 + 1] = Digit[c & 0X0F];
- }
-
- return new String(out);
- }
-
- public static void main(String[] args) {
- String fileName = "D://code//cc.png";
- String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";
- String outImage = "D://code//11.png";
-
- String result = getImgeHexStringByUrl(url);
- System.out.println(result);
- saveImage(result,fileName,"png");
-
- String result1 = getImgeHexStringByLocalUrl(fileName);
- System.out.println(result1);
- saveImage(result1,outImage,"png");
- }
-
- }
經過url下載圖片
在給定url的狀況下,可將url所訪問的圖片下載至本地。具體代碼以下:dom
- import java.io.BufferedInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.URL;
-
- public class downimageUtil {
-
- private static final String filePath = "C://Users//lizhihui//Desktop//";
-
-
- public String saveToFile(String destUrl) {
- String fileName = "";
- FileOutputStream fos = null;
- BufferedInputStream bis = null;
- HttpURLConnection httpUrl = null;
- URL url = null;
- int BUFFER_SIZE = 1024;
- byte[] buf = new byte[BUFFER_SIZE];
- int size = 0;
- try {
- url = new URL(destUrl);
- httpUrl = (HttpURLConnection) url.openConnection();
- httpUrl.connect();
- bis = new BufferedInputStream(httpUrl.getInputStream());
- for (String string : destUrl.split("/")) {
- if (string.contains("png") || string.contains("png") || string.contains("gif")) {
- fileName = string;
- }
- }
- fos = new FileOutputStream(filePath + fileName);
- while ((size = bis.read(buf)) != -1) {
- fos.write(buf, 0, size);
- }
- fos.flush();
- } catch (IOException e) {
- } catch (ClassCastException e) {
- } finally {
- try {
- fos.close();
- bis.close();
- httpUrl.disconnect();
- } catch (IOException e) {
- } catch (NullPointerException e) {
- }
- }
- return filePath + fileName;
- }
-
- public static void main(String[] args) {
- downimageUtil dw = new downimageUtil();
- String url = "https://images0.cnblogs.com/blog/536814/201412/051633343733092.png";
- System.out.println(dw.saveToFile(url));
- }
- }
到此,對於圖片的處理結束,這是在寫圖片壓縮服務器時所用到的部分技術,固然在此基本上有所改進,在此再也不一一列舉,對於圖片的壓縮方法後續也會整理出來,歡迎查看!雖然寫出來了,但還沒進行壓力測試,優化等一系列後續工做。就先這樣吧......測試
轉載自:https://blog.csdn.net/hh12211221/article/details/74639049優化