❶ java中如何把一個圖片轉換成二進制流存入到類中啊
1.將Image圖像文件存入到資料庫中
我們知道資料庫里的Image類型的數據是"二進制數據",因此必須將圖像文件轉換成位元組數組才能存入資料庫中.
要這里有關數據的操作略寫,我將一些代碼段寫成方法,方便直接調用.
//根據文件名(完全路徑)
public byte[] SetImageToByteArray(string fileName)
{
FileStream fs = new FileStream(fileName, FileMode.Open);
int streamLength = (int)fs.Length;
byte[] image = new byte[streamLength];
fs.Read(image, 0, streamLength);
fs.Close();
return image;
}
//另外,在ASP.NET中通過FileUpload控制項得到的圖像文件可以通過以下方法
public byte[] SetImageToByteArray(FileUpload FileUpload1)
{
Stream stream = FileUpload1.PostedFile.InputStream;
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
stream.Read(photo, 0, FileUpload1.PostedFile.ContentLength);
stream.Close();
return photo;
}
2.從SQL Server資料庫讀取Image類型的數據,並轉換成bytes[]或Image圖像文件
//要使用SqlDataReader要載入using System.Data.SqlClient命名空間
//將資料庫中的Image類型轉換成byte[]
public byte[] SetImage(SqlDataReader reader)
{
return (byte[])reader["Image"];//Image為資料庫中存放Image類型欄位
}
//將byte[]轉換成Image圖像類型
//載入以下命名空間using System.Drawing;/using System.IO;
using System.Data.SqlClient;*/
public Image SetByteToImage(byte[] mybyte)
{
Image image;
MemoryStream mymemorystream = new MemoryStream(mybyte,0, mybyte.Length);
image = Image.FromStream(mymemorystream);
return image;
}
❷ Java中如何把圖片轉換成二進制流
Java中將圖片轉為二進制流只需要使用FileImageInputStream取得圖片文件,然後使用ByteArrayOutputStream 寫入到二進制流中即可,下面是詳細代碼:
//圖片到byte數組
publicbyte[]image2byte(Stringpath){
byte[]data=null;
FileImageInputStreaminput=null;
try{
input=newFileImageInputStream(newFile(path));
ByteArrayOutputStreamoutput=newByteArrayOutputStream();
byte[]buf=newbyte[1024];
intnumBytesRead=0;
while((numBytesRead=input.read(buf))!=-1){
output.write(buf,0,numBytesRead);
}
data=output.toByteArray();
output.close();
input.close();
}
catch(FileNotFoundExceptionex1){
ex1.printStackTrace();
}
catch(IOExceptionex1){
ex1.printStackTrace();
}
returndata;
}
另外,如果需要將byte[]存回圖片或轉為String,則:
//byte數組到圖片
publicvoidbyte2image(byte[]data,Stringpath){
if(data.length<3||path.equals(""))return;
try{
=newFileImageOutputStream(newFile(path));
imageOutput.write(data,0,data.length);
imageOutput.close();
System.out.println("MakePicturesuccess,Pleasefindimagein"+path);
}catch(Exceptionex){
System.out.println("Exception:"+ex);
ex.printStackTrace();
}
}
//byte數組到16進制字元串
publicStringbyte2string(byte[]data){
if(data==null||data.length<=1)return"0x";
if(data.length>200000)return"0x";
StringBuffersb=newStringBuffer();
intbuf[]=newint[data.length];
//byte數組轉化成十進制
for(intk=0;k<data.length;k++){
buf[k]=data[k]<0?(data[k]+256):(data[k]);
}
//十進制轉化成十六進制
for(intk=0;k<buf.length;k++){
if(buf[k]<16)sb.append("0"+Integer.toHexString(buf[k]));
elsesb.append(Integer.toHexString(buf[k]));
}
return"0x"+sb.toString().toUpperCase();
}
❸ java里怎樣把文件轉換成二進制
轉換文件成為二進制數據並保存的Java代碼:
取出數據並還原文件到本地的java代碼:
[java]view plain//讀取資料庫二進制文件
publicvoidreaderJpg()throwsSQLException
{
connection=connectionManager.getconn();//自己連接自己的資料庫
StringsqlString="selectimagesfromsave_imagewhereid=4";//從資料庫中讀出要還原文件的二進制碼,這里我讀的是自己的資料庫id為4的文件
Filefile=newFile("E:\1.jpg");//本地生成的文件
if(!file.exists())
{
try{
file.createNewFile();
}catch(Exceptione){
e.printStackTrace();
}
}
try{
byte[]Buffer=newbyte[4096*5];
statement=connection.prepareStatement(sqlString);
resultSet=statement.executeQuery();
if(resultSet.next())
{
FileOutputStreamoutputStream=newFileOutputStream(file);
InputStreamiStream=resultSet.getBinaryStream("images");//去欄位用getBinaryStream()
intsize=0;
while((size=iStream.read(Buffer))!=-1)
{
System.out.println(size);
outputStream.write(Buffer,0,size);
}
}
}catch(Exceptione){
e.printStackTrace();
}
}
❹ java如何把圖片轉換成二進制並存到oracle的blob中,求代碼
importjavax.imageio.ImageIO;
importjava.awt.image.BufferedImage;
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.File;
importjava.io.IOException;
publicclassImageUtils{
publicstaticvoidmain(String[]args){
Stringstr=img2Binary("C:\Users\hny\Desktop\favicon.jpg");
System.out.println(str);
binary2Img("C:\Users\hny\Desktop\favicon2.jpg",str);
}
/**
*圖片轉二進制字元串
*
*@parampath圖片路徑
*@return
*/
publicstaticStringimg2Binary(Stringpath){
Filefile=newFile(path);
if(!file.exists()){
returnnull;
}
try{
BufferedImagebi=ImageIO.read(file);
ByteArrayOutputStreambaos=newByteArrayOutputStream();
Stringsuffix=getSuffix(path);
ImageIO.write(bi,suffix,baos);
byte[]bytes=baos.toByteArray();
returnnewsun.misc.BASE64Encoder().encodeBuffer(bytes).trim();
}catch(IOExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*字元串轉圖片文件
*
*@parampath圖片路徑
*@paramimgBinary圖片字元串
*/
publicstaticvoidbinary2Img(Stringpath,StringimgBinary){
try{
Filefile=newFile(path);
byte[]bytes1=newsun.misc.BASE64Decoder().decodeBuffer(imgBinary);
ByteArrayInputStreams=newByteArrayInputStream(bytes1);
BufferedImagebi1=ImageIO.read(s);
Stringsuffix=getSuffix(path);
ImageIO.write(bi1,suffix,file);
}catch(IOExceptione){
e.printStackTrace();
}
}
/**
*獲取圖片後綴名
*
*@parampath
*@return
*/
privatestaticStringgetSuffix(Stringpath){
intindex=path.contains(".")?path.lastIndexOf("."):-1;
if(index>-1){
returnpath.substring(index+1);
}
returnnull;
}
}
❺ java把圖片轉換成二進制流
public static void main(String[] args) throws Exception {
File file = new File("d:\L.jpg");//圖片
FileInputStream fis = new FileInputStream(file);//把圖片變成流
FileOutputStream fos = new FileOutputStream(new File("E:\L.jpg")); //把圖片流寫入E盤
byte[] read = new byte[1024]; //每次讀取的位元組 可以自己定義 256 512 1024 2048 等。。。
int len = 0;
while((len = fis.read(read))!= -1){ //讀取變成流的圖片
fos.write(read,0,len);//寫入圖片
}
fis.close();//關閉輸入流
fos.close();//關閉輸出流
}
❻ java怎麼實現讀取一個文件,拿到二進制流
Java讀取二進制文件,以位元組為單位進行讀取,還可讀取圖片、音樂文件、視頻文件等,
在Java中,提供了四種類來對文件進行操作,分別是InputStream OutputStream Reader Writer ,前兩種是對位元組流的操作,後兩種則是對字元流的操作。
示例代碼如下:
public static void readFileByBytes(String fileName){
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("一次讀一個");
// 一次讀一個位元組
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}