這篇文章主要介紹了如何在java中將圖片轉(zhuǎn)化為二進(jìn)制字符串,此處給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考價(jià)值,需要的朋友可以參考下:

創(chuàng)新互聯(lián)長(zhǎng)期為千余家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開(kāi)放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為屏山企業(yè)提供專業(yè)的網(wǎng)站制作、成都網(wǎng)站建設(shè),屏山網(wǎng)站改版等技術(shù)服務(wù)。擁有十多年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開(kāi)發(fā)。
public static String getImgStr(String imgFile){
//將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對(duì)其進(jìn)行Base64編碼處理
InputStream in = null;
byte[] data = null;
//讀取圖片字節(jié)數(shù)組
try
{
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return new String(Base64.encodeBase64(data));
}--
利用以上的思路寫的一個(gè)測(cè)試
public class ReadImageTest {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream(new File("C:\\Users\\luzhifei\\Pictures\\hc_logo.png"));
String picStr="";
byte[] read = null;
int len = 0;
read= new byte[fis.available()];
fis.read(read);
String baseStr= Base64.getEncoder().encodeToString(read);
//System.out.println( baseStr);
byte[] op= Base64.getDecoder().decode(baseStr);
// System.out.println(new String(op));
FileOutputStream fos = new FileOutputStream(new File("d:\\temp\\1.jpg"));
fos.write(op,0,op.length );
fos.flush();
fos.close();
}
}但是available()有一定的限制。
為了穩(wěn)妥,嚴(yán)重建議采取以下方式:
public static void imageToBase64Str() throws IOException{
FileInputStream fis = new FileInputStream(new File("C:\\Users\\luzhifei\\Pictures\\hc_logo.png"));
byte[] read = new byte[1024];
int len = 0;
List<byte[]> blist=new ArrayList<byte[]>();
int ttllen=0;
while((len = fis.read(read))!= -1){
byte[] dst=new byte[len];
System.arraycopy(read, 0, dst, 0, len);
ttllen+=len;
blist.add(dst);
}
fis.close();
byte[] dstByte=new byte[ttllen];
int pos=0;
for (int i=0;i<blist.size();i++){
if (i==0){
pos=0;
}
else{
pos+=blist.get(i-1).length;
}
System.arraycopy(blist.get(i), 0, dstByte, pos, blist.get(i).length);
}
String baseStr= Base64.getEncoder().encodeToString(dstByte);
byte[] op= Base64.getDecoder().decode(baseStr);
FileOutputStream fos = new FileOutputStream(new File("d:\\temp\\2.jpg"));
fos.write(op,0,op.length );
fos.flush();
fos.close();
}到此這篇關(guān)于如何在java中將圖片轉(zhuǎn)化為二進(jìn)制字符串的文章就介紹到這了,更多相關(guān)的內(nèi)容請(qǐng)搜索創(chuàng)新互聯(lián)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持創(chuàng)新互聯(lián)!
網(wǎng)站名稱:如何在java中將圖片轉(zhuǎn)化為二進(jìn)制字符串
分享網(wǎng)址:http://chinadenli.net/article4/gsgdoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、企業(yè)建站、軟件開(kāi)發(fā)、網(wǎng)站營(yíng)銷、全網(wǎng)營(yíng)銷推廣、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)