Java實現圖片與Base64編碼互轉
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importsun.misc.BASE64Decoder;
importsun.misc.BASE64Encoder;
publicclassBase64Image{
publicstaticvoidmain(String[]args){
//測試從Base64編碼轉換為圖片文件
StringstrImg="自己寫哈";
GenerateImage(strImg,"D:\wangyc.jpg");
//測試從圖片文件轉換為Base64編碼
System.out.println(GetImageStr("d:\wangyc.jpg"));
}
publicstaticStringGetImageStr(StringimgFilePath){//將圖片文件轉化為位元組數組字元串,並對其進行Base64編碼處理
byte[]data=null;
//讀取圖片位元組數組
try{
InputStreamin=newFileInputStream(imgFilePath);
data=newbyte[in.available()];
in.read(data);
in.close();
}catch(IOExceptione){
e.printStackTrace();
}
//對位元組數組Base64編碼
BASE64Encoderencoder=newBASE64Encoder();
returnencoder.encode(data);//返回Base64編碼過的位元組數組字元串
}
(StringimgStr,StringimgFilePath){//對位元組數組字元串進行Base64解碼並生成圖片
if(imgStr==null)//圖像數據為空
returnfalse;
BASE64Decoderdecoder=newBASE64Decoder();
try{
//Base64解碼
byte[]bytes=decoder.decodeBuffer(imgStr);
for(inti=0;i<bytes.length;++i){
if(bytes[i]<0){//調整異常數據
bytes[i]+=256;
}
}
//生成jpeg圖片
OutputStreamout=newFileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
returntrue;
}catch(Exceptione){
returnfalse;
}
}
}
㈡ vue 上傳圖片時 base64 怎麼傳到java後台
1、org.apache.commons.codec.binary.Base64.decodeBase64(這里傳入src屬性里的base64 的一串字元串);
2、返回值是一個Byte[];
3、位元組流傳送到文件。
備註:這里Base64隻是提供預覽,其實可以保留原始的url傳給後台的。
㈢ JAVA怎麼將pdf的base64轉換成jpg的base64
package com.aiait.base.util;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.aiait.base.service.impl.base.SearchServiceImpl;
import org.apache.pdfbox.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class PDFUtil {
// logger
private static final Logger lOGGER = LoggerFactory.getLogger(PDFUtil.class);
public static void main(String[] args) {
// pdfTojpg("C://Test//eClaimPDF//1//Others.pdf","C://Test//eClaimPDF//WrittenConfirmation.jpg");
Date timeDiffE = null;
Date timeDiffL = null;
timeDiffE = new Date();
base64PdfToJpg(pdfBase64);
timeDiffL = new Date();
lOGGER.info("base64PdfToJpg use time: " + getDiffTime(timeDiffL, timeDiffE) + "s");
}
private static String base64PdfToJpg(String base64Pdf) {
String jpg_base64 = null;
int pdfdpi = 400;
BASE64Decoder decoder = new BASE64Decoder();
byte[] pdf_bytes = null;
try {
pdf_bytes = decoder.decodeBuffer(base64Pdf);
} catch (IOException e1) {
e1.printStackTrace();
}
try (final PDDocument document = PDDocument.load(pdf_bytes)) {
int size = document.getNumberOfPages();
/*圖像合並使用參數*/
// 定義寬度
int width = 0;
// 保存一張圖片中的RGB數據
int[] singleImgRGB;
// 定義高度,後面用於疊加
int shiftHeight = 0;
//保存每張圖片的像素值
BufferedImage imageResult = null;
// 利用PdfBox生成圖像
PDDocument pdDocument = document;
PDFRenderer renderer = new PDFRenderer(pdDocument);
/*根據總頁數, 按照50頁生成一張長圖片的邏輯, 進行拆分*/
// 每50頁轉成1張圖片
int pageLength = size; //有多少轉多少
// 總計循環的次數
int totalCount = pdDocument.getNumberOfPages() / pageLength + 1;
for (int m = 0; m < totalCount; m++) {
for (int i = 0; i < pageLength; i++) {
int pageIndex = i + (m * pageLength);
if (pageIndex == pdDocument.getNumberOfPages()) {
System.out.println("m = " + m);
break;
}
// 96為圖片的dpi,dpi越大,則圖片越清晰,圖片越大,轉換耗費的時間也越多
BufferedImage image = renderer.renderImageWithDPI(pageIndex, 106, ImageType.RGB);
int imageHeight = image.getHeight();
int imageWidth = image.getWidth();
if (i == 0) {
//計算高度和偏移量
//使用第一張圖片寬度;
width = imageWidth;
// 保存每頁圖片的像素值
// 加個判斷:如果m次循環後所剩的圖片總數小於pageLength,則圖片高度按剩餘的張數繪制,否則會出現長圖片下面全是黑色的情況
if ((pdDocument.getNumberOfPages() - m * pageLength) < pageLength) {
imageResult = new BufferedImage(width, imageHeight * (pdDocument.getNumberOfPages() - m * pageLength), BufferedImage.TYPE_INT_RGB);
} else {
imageResult = new BufferedImage(width, imageHeight * pageLength, BufferedImage.TYPE_INT_RGB);
}
} else {
// 將高度不斷累加
shiftHeight += imageHeight;
}
singleImgRGB = image.getRGB(0, 0, width, imageHeight, null, 0, width);
imageResult.setRGB(0, shiftHeight, width, imageHeight, singleImgRGB, 0, width);
}
// System.out.println("m = " + m);
File outFile = new File("C://Test//eClaimPDF//WrittenConfirmation.png");
System.out.println(outFile.getName());
// 寫圖片
ImageIO.write(imageResult, "png", outFile);
// 這個很重要,下面會有說明
shiftHeight = 0;
}
pdDocument.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
ImageIO.write(imageResult, "png", baos);//寫入流中
byte[] jpg_Bytes = baos.toByteArray();//轉換成位元組
BASE64Encoder encoder = new BASE64Encoder();
jpg_base64 = encoder.encodeBuffer(jpg_Bytes).trim();//轉換成base64串
jpg_base64 = jpg_base64.replaceAll(" ", "").replaceAll(" ", "");//刪除
// System.out.println("值為:"+"data:image/jpg;base64,"+jpg_base64);
} catch (Exception e) {
e.printStackTrace();
}
return "data:image/jpg;base64,"+jpg_base64;
}
// private static String base64PdfToJpg(String base64Pdf) {
// String jpg_base64 = null;
// int pdfdpi = 400;
//
// BASE64Decoder decoder = new BASE64Decoder();
// byte[] pdf_bytes = null;
// try {
// pdf_bytes = decoder.decodeBuffer(base64Pdf);
// } catch (IOException e1) {
// e1.printStackTrace();
// }
//
// try (final PDDocument document = PDDocument.load(pdf_bytes)) {
// int size = document.getNumberOfPages();
// for (int i = 0; i < size; i++) {
// BufferedImage image = new PDFRenderer(document).renderImageWithDPI(i, pdfdpi, ImageType.RGB);
// BufferedImage image = new PDFRenderer(document).
//
// ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
// ImageIO.write(image, "jpg", baos);//寫入流中
// byte[] jpg_Bytes = baos.toByteArray();//轉換成位元組
// BASE64Encoder encoder = new BASE64Encoder();
// jpg_base64 = encoder.encodeBuffer(jpg_Bytes).trim();//轉換成base64串
// jpg_base64 = jpg_base64.replaceAll(" ", "").replaceAll(" ", "");//刪除
//
// System.out.println("值為:"+"data:image/jpg;base64,"+jpg_base64);
//
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// return "data:image/jpg;base64,"+jpg_base64;
// }
private static void pdfTojpg(String pdfFilePath, String jpgFilePath) {
File pdfFile = new File(pdfFilePath);
int idx = jpgFilePath.lastIndexOf('.');
String jpgprefix = StringUtils.substring(jpgFilePath, 0, idx);
int pdfdpi = 400;
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes = null;
try {
bytes = decoder.decodeBuffer(pdfBase64);
} catch (IOException e1) {
e1.printStackTrace();
}
// try (final PDDocument document = PDDocument.load(pdfFile, "")) {
try (final PDDocument document = PDDocument.load(bytes)) {
int size = document.getNumberOfPages();
for (int i = 0; i < size; i++) {
BufferedImage image = new PDFRenderer(document).renderImageWithDPI(i, pdfdpi, ImageType.RGB);
/*
* ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
* ImageIO.write(image, "jpg", baos);//寫入流中 byte[] imgBytes =
* baos.toByteArray();//轉換成位元組 BASE64Encoder encoder = new BASE64Encoder();
* String png_base64 = encoder.encodeBuffer(imgBytes).trim();//轉換成base64串
* png_base64 = png_base64.replaceAll(" ", "").replaceAll(" ", "");//刪除
*
* System.out.println("值為:"+"data:image/jpg;base64,"+png_base64);
*/
File jpgFile = new File(jpgprefix + "_" + i + ".jpg");
ImageIO.write(image, "jpg", jpgFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static Double getDiffTime(Date lateTime, Date earlyTime) {
DecimalFormat df=new DecimalFormat("0.00");//設置保留位數
return Double.valueOf(df.format((double)(lateTime.getTime() - earlyTime.getTime()) / 1000));
}
public static String pdfBase64 = "***" //from web網頁鏈接, upload a PDF to get the base64 string (Base64 - Online Base64 decoder and encoder)
}
㈣ java將base64轉換成圖片並保存在指定路徑下ImageIO.write(bi1,"png",w2)提示image==null
這個簡單啊
(1)把獲取url流轉為bitmap
(2)把bitmap再轉為base64
(Stringurlpath){
Bitmapmap=null;
try{
URLurl=newURL(urlpath);
URLConnectionconn=url.openConnection();
conn.connect();
InputStreamin;
in=conn.getInputStream();
map=BitmapFactory.decodeStream(in);
//TODOAuto-generatedcatchblock
}catch(IOExceptione){
e.printStackTrace();
}
returnmap;
}
第二步
/**
*bitmap轉為base64
*@parambitmap
*@return
*/
(Bitmapbitmap){
Stringresult=null;
ByteArrayOutputStreambaos=null;
try{
if(bitmap!=null){
baos=newByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
baos.flush();
baos.close();
byte[]bitmapBytes=baos.toByteArray();
result=Base64.encodeToString(bitmapBytes,Base64.DEFAULT);
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
try{
if(baos!=null){
baos.flush();
baos.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnresult;
}
㈤ java中如何用base64解碼圖片,並返回圖片,不保存。
給你發個我以前的工具類吧、
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ImageChange {
/**
* 從path這個地址獲取一張圖片然後轉為base64碼
* @param imgName 圖片的名字 如:123.gif(是帶後綴的)
* @param path 123.gif圖片存放的路徑
* @return
* @throws Exception
*/
public static String getImageFromServer(String imgName,String path)throws Exception{
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
File f = new File(path+imgName);
if(!f.exists()){
f.createNewFile();
}
BufferedImage bi = ImageIO.read(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "gif", baos);
byte[] bytes = baos.toByteArray();
return encoder.encodeBuffer(bytes).trim();
}
/**
* 將一個base64轉換成圖片保存在 path 文件夾下 名為imgName.gif
* @param base64String
* @param path 是一個文件夾路徑
* @param imgName 圖片名字(沒有後綴)
* @throws Exception
*/
public static String savePictoServer(String base64String,String path,String imgName)throws Exception{
BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream s = new ByteArrayInputStream(bytes1);
BufferedImage bi1 =ImageIO.read(s);
Date timeCur = new Date();
SimpleDateFormat fmtYY = new SimpleDateFormat("yyyy");
SimpleDateFormat fmtMM = new SimpleDateFormat("MM");
SimpleDateFormat fmtDD = new SimpleDateFormat("dd");
String strYY = fmtYY.format(timeCur);
String strMM = fmtMM.format(timeCur);
String strDD = fmtDD.format(timeCur);
String realPath = path+"/"+strYY+"/"+strMM+"/"+strDD;
File dir=new File(realPath);
if(!dir.exists()){
dir.mkdirs();
}
String fileName=path+"\\"+strYY+"\\"+strMM+"\\"+strDD +"\\"+imgName+".gif";
File w2 = new File(fileName);//可以是jpg,png,gif格式
ImageIO.write(bi1, "jpg", w2);//不管輸出什麼格式圖片,此處不需改動
return fileName;
}
public static void main(String[] args) throws Exception {
System.out.println(getImageFromServer("001001.gif","d:"));
}
}
㈥ java 怎麼將base64轉成照片
Stringfile="......base64..........";
StringfileName=test+".jpg";
StringfilePath="/home/"+fileName;
byte[]json=null;
try{
json=file.getBytes("UTF-8");
json=Base64.decodeBase64(json);
Filefiles=newFile(filePath);
=null;
try{
imageOutput=newFileImageOutputStream(files);
imageOutput.write(json,0,json.length);
}catch(FileNotFoundExceptione){
_log.info(e.getMessage());
}catch(IOExceptione){
_log.info(e.getMessage());
}
try{
imageOutput.close();
}catch(IOExceptione){
_log.info(e.getMessage());
}
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}
請採納,謝謝
㈦ Java:為什麼傳輸圖片是常用base64字元串轉碼,而不是直接傳輸byte[]呢求解
先說說base64吧:對於圖片來說,一個位元組佔八位,如果都換成byte[]的話,會很長,不便於傳輸,那麼就把沒6個位元組來對應一個新的字元(如010011是19,對應base64編碼的T),,所以這個目的主要是精簡數據,便於傳輸;
另外常用的用途是:做不嚴格的加密用,比如常見的磁力鏈接,你懂的;因為它相對於嚴格加密省時省力,速度快,況且可恢復(如果用MD5就不行)
㈧ java怎麼把base64的圖片顯示到頁面
base64可以轉成二進制數組。然後直接往外輸出就好了。
㈨ 將base64位轉換成png圖片的java代碼
//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;
}
}
希望可以幫到你。
㈩ java轉化BASE64為PNG的異常情況
那是部分軟體的問題,不是所有的軟體都支持這樣的base64的。
~
~
~
~~~~~~~~~~~~~~~~~~~