在線圖片轉base64編碼
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
/** * 下載圖片並轉換成base64格式 * * @param imageUrl 圖片URL * * @return 圖片base64編碼 */ private String downLoadImageToBase64(String imageUrl) throws Exception{ logger.info("chainserviceImpl.downLoadImageToBase64,start,imageUrl:{}",imageUrl); if(StringUtils.isBlank(imageUrl)){ throw new JobException("人臉識別,人臉圖片url不能為空"); } //下載圖片 BufferedImage image =null; URL url = new URL(imageUrl); image = ImageIO.read(url); ByteArrayOutputStream bos = new ByteArrayOutputStream(); String type = StringUtils.substring(imageUrl, imageUrl.lastIndexOf(".") + 1); ImageIO.write(image, type, bos); byte[] imageBytes = bos.toByteArray(); String imageString = Base64.encode(imageBytes); bos.close(); logger.info("chainserviceImpl.downLoadImageToBase64,end,imageUrl:{}",imageUrl); if(StringUtils.isBlank(imageString)){ throw new JobException("獲取人臉圖片base64編碼失敗"); } return imageString; }
本地圖片轉base64編碼
import java.nio.file.Files;
import java.nio.file.Paths;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
/** * 本地圖片轉base64編碼 * * @param filePath 文件圖片所在路徑 * * @return base64編碼 */ public String imageToBase64(String filePath) throws Exception{ if(StringUtils.isBlank(filePath)){ return null; } String encode=""; try{ byte[] bytes = Files.readAllBytes(Paths.get(filePath)); encode = Base64.encode(bytes); }catch (Exception e){ throw e; } return encode; }
base64編碼轉圖片
import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /** * base64編碼轉成圖片文件 * * @param base64 圖片的base64編碼 * @param filePath 圖片文件的保存路徑 * * @return * @throws Exception */ public static String decryptByBase64(String base64, String filePath) throws Exception{ if (base64 == null && filePath == null) { return "生成文件失敗,請給出相應的數據。"; } try { Files.write(Paths.get(filePath),Base64.decode(base64), StandardOpenOption.CREATE); } catch (IOException e) { throw e; } return "指定路徑下生成文件成功!"; }
