导航:首页 > 编程语言 > java图片转二进制

java图片转二进制

发布时间:2025-02-28 07:37:25

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;
}

阅读全文

与java图片转二进制相关的资料

热点内容
深受顾客喜爱的程序员雇佣平台 浏览:47
程序员的招聘 浏览:749
pdf嵌入视频 浏览:846
苹果手机怎么安卓系统运行 浏览:558
学案文件夹长什么样子 浏览:677
ps虚设在哪个文件夹 浏览:591
如何下载富豪安卓 浏览:577
听动漫音乐的app哪个好 浏览:741
为什么苹果手机用安卓系统好 浏览:774
数控车床ck6130编程 浏览:912
百度app怎么登录淘宝 浏览:755
镇江ug电脑编程培训机构 浏览:446
成为算法工程师需要哪些学习 浏览:163
如何连接cuda服务器 浏览:312
我的世界如何用命令牌命令铁傀儡 浏览:532
新斗罗大陆怎么进太挤的服务器 浏览:638
文件夹显示不出来咋办 浏览:180
手机pdf插件下载 浏览:66
快递小哥也疯狂解压 浏览:868
阿里云服务器如何安装两个站点 浏览:614