⑴ 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压缩至32K以下后的图片base64码
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;
}
}
}
⑷ 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解码图片,并返回图片,不保存。
给你发个我以前的工具类吧、
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
这个简单啊
(1)把获取url流转为bitmap
(2)把bitmap再转为base64
public static Bitmap getBitMBitmap(String urlpath) {
Bitmap map = null;
try {
URL url = new URL(urlpath);
URLConnection conn = url.openConnection();
conn.connect();
InputStream in;
in = conn.getInputStream();
map = BitmapFactory.decodeStream(in);
// TODO Auto-generated catch block
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
第二步
/**
* bitmap转为base64
* @param bitmap
* @return
*/
public static String bitmapToBase64(Bitmap bitmap) {
String result = null;
ByteArrayOutputStream baos = null;
try {
if (bitmap != null) {
baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
baos.flush();
baos.close();
byte[] bitmapBytes = baos.toByteArray();
result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (baos != null) {
baos.flush();
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
有什么问题提问就好
⑻ java转化BASE64为PNG的异常情况
那是部分软件的问题,不是所有的软件都支持这样的base64的。
~
~
~
~~~~~~~~~~~~~~~~~~~
⑼ Java 在for循环内用base64解析多张图片问题,求高手指点
前提这些图片必须先经过base64进行编码。测试时,循环遍历每一张图片经过base64编码后的码值。只要码值不同,解析方法正确,图片不会出现相同
⑽ 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();
}
请采纳,谢谢