当前位置:首页 » 图片资讯 » 二进制图片怎么保存文件
扩展阅读
美女健身跳河视频 2023-08-31 22:08:21
西方贵族美女照片真人 2023-08-31 22:08:15

二进制图片怎么保存文件

发布时间: 2022-05-14 05:47:47

① php怎样将二进制流存到文件中

整形转化成2二进制可以用base_convert:

$str=0x8000;

echo$str2=base_convert($str,16,2);
echo'<br>';
echobase_convert($str2,2,16);
[code]

字符串文件等可以考虑用pack和unpack转化成二进制

[code=PHP]
$file1='F:/46.gif';//随便拷一个图片作为测试用
$file2='F:/test.txt';//生成的二进制流保存在这个文件里
$file3='F:/47.gif';//由二进制流还原成的文件

$size=filesize($file1);

echo'文件大小为:'.$size;
echo" <br>转化为二进制...";

$content=file_get_contents($file1);
$content=bstr2bin($content);


$fp=fopen($file2,'w');
fwrite($fp,$content);
fclose($fp);

$size2=filesize($file2);

echo'转化成二进制后文件大小为:'.$size2;

$content=bin2bstr($content);

$fp=fopen($file3,'w');
fwrite($fp,$content);
fclose($fp);


functionbin2bstr($input)
//Convertabinaryexpression(e.g.,"100111")intoabinary-string
{
if(!is_string($input))returnnull;//Sanitycheck

//Packintoastring
$input=str_split($input,4);
$str='';
foreach($inputas$v)
{
$str.=base_convert($v,2,16);
}

$str=pack('H*',$str);

return$str;
}

functionbstr2bin($input)
//Binaryrepresentationofabinary-string
{
if(!is_string($input))returnnull;//Sanitycheck

//Unpackasahexadecimalstring
$value=unpack('H*',$input);

//Outputbinaryrepresentation
$value=str_split($value[1],1);
$bin='';
foreach($valueas$v)
{
$b=str_pad(base_convert($v,16,2),4,'0',STR_PAD_LEFT);

$bin.=$b;
}

return$bin;
}

② SQL数据库 二进制图片如何导出成文件

SQL数据库 二进制图片如何导出成文件
1.将图片以二进制存入数据库
//保存图片到数据库
protected void Button1_Click(object sender, EventArgs e)
{
//图片路径
string strPath = "~/photo/03.JPG";
string strPhotoPath = Server.MapPath(strPath);
//读取图片
FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
//存入
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) ";
strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length);
myComm.Parameters["@photoBinary"].Value = photo;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
}
2.读取二进制图片在页面显示
//读取图片
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myConn.Open();
SqlDataReader dr = myComm.ExecuteReader();
while (dr.Read())
{
byte[] photo = (byte[])dr["personPhoto"];
this.Response.BinaryWrite(photo);
}
dr.Close();
myConn.Close();

SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
this.Response.BinaryWrite(photo);
3.设置Image控件显示从数据库中读出的二进制图片

③ 把图片文件转成二进制保存txt然后保存的代码

材料:在电脑上面准备ocr文字识别工具。

方法:

  1. 运行ocr文字识别工具,选择上面功能栏中的“极速识别”功能。

  2. 点击左上角的“添加文件”,把需要转换的图片文字添加进去。

  3. 在上面选择文件的“识别格式”。

  4. 点击操作下面的“开始识别”按钮。

希望上面的方法可以帮助到你哦!

④ 如何将文本中的二进制数据保存为一个文件

不知道你是不是想问的这个,可以参考一下

123456789101112131415

#include <fstream>#include <iostream>#include <string>using namespace std; int main() { ifstream fileIn("readfile.txt"); ofstream fileOut("writefile.txt", ofstream::binary); string inputs; while (getline(fileIn,inputs)) { fileOut << inputs << endl; } fileIn.close(); fileOut.close();}

⑤ C#编程:如何把二进制内容保存成文件(AVI或图片)

你所谓的二进制的值 应该是一个字节数组 byte[]
那么只要这一个方法就可以了

System.IO.File.WriteAllBytes("c:\111.avi",byte[]);

⑥ 请进!!如何把绘制的图片直接以二进制流存入数据库(java)

怎样在mysql中存储比较大的图片?
如果你想把二进制的数据,比如说图片文件和HTML文件,直接保存在你的MySQL数据库,那么这篇文章就是为你而写的!我将告诉你怎样通过HTML表单来储存这些文件,怎样访问和使用这些文件。

一、本文概述

本文的主要内容如下:

* 在MySQL中建立一个新的数据库
* 一个怎样储存文件的例子程序
* 一个怎样访问文件的例子程序

二、在MySQL中建立一个新的database

首先,你必须在你的MySQL中建立一个新的数据库,我们将会把那些二进制文件储存在这个数据库里。在例子中我会使用下列结构,为了建立数据库,你必须做下列步骤:

1. 进入MySQL控制器
2. 输入命令"create database binary_data;"
3. 输入命令"use binary_data;"

输入如下命令:

"CREATE TABLE binary_data ( id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,description CHAR(50), bin_data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50));" (不能断行)

如果没有意外,数据库 和 表 应该建立好了。

三、一个怎样储存文件的例子程序

用这个例子你可以通过Html表单将文件传输到数据库中。

store.php3

// store.php3 - by Florian Dittmer

?>

// 如果提交了表单,代码将被执行:

if ($submit) {

// 连接到数据库
// (你可能需要调整主机名,用户名和密码)

MYSQL_CONNECT( "localhost", "root", "password");
MySQL_select_db( "binary_data");
$data = addslashes(fread(fopen($form_data, "r"), filesize($form_data)));
$result=MYSQL_QUERY( "INSERT INTO binary_data (description,bin_data,filename,filesize,filetype)VALUES ('$form_description','$data','$form_data_name','$form_data_size','$form_data_type')");
$id= MySQL_insert_id();
print "This file has the following Database ID: $id";
MYSQL_CLOSE();
} else {

// 否则显示储存新数据的表单

?>

@MySQL_select_db( "binary_data");
$query = "select bin_data,filetype from binary_data where id=$id";
$result = @MYSQL_QUERY($query);
$data = @MYSQL_RESULT($result,0, "bin_data");
$type = @MYSQL_RESULT($result,0, "filetype");
Header( "Content-type: $type");
echo $data;
};
?>
程序必须知道要访问那个文件, 你必须将ID作为一个参数。

例如: 一个文件在数据库中的ID为2. 你可以这样调用它: getdata.php3?id=2

如果你将图片储存在数据库里, 你可以向调用图片一样调用它。

Example: 一个图片文件在数据库中的ID为3. 你可以这样调用它:

五、怎样储存大于1MB的文件

如果你想储存大于1MB的文件,你必须对你的程序、PHP设置、SQL设置进行许多修改。

下面几条也许可以帮助你储存小于24MB的文件:

1) 修改 store.php3,将 MAX_FILE_SIZE 的值改成 24000000。

2) 修改你的PHP设置,在一般情况下,PHP只允许小于2MB的文件,你必须将max_filesize(在php.ini中)的值改成24000000

3) 去掉MYSQL的数据包大小限制,在一般情况下 MYSQL 小于1 MB的数据包。

4) 你必须用以下参数重启你的MYSQL :/usr/local/bin/safe_MySQLd -O key_buffer=16M -O table_cache=128 -O sort_buffer=4M -O record_buffer=1M -O max_allowed_packet=24M

5) 如果仍然出错:可能是超时错误,如果你通过一个很慢的连接来储存一个很大的文件,PHP缺省的时间限制为30秒。你可以将max_execution_time(在php.ini中)的值改为-1

下面是一个老外写的,可以读

Saving Images in MySQL

Sometimes, it's more convenient to save images in a database than as files.
MySQL and PHP make it very easy to do this. In this article, I will describe
how to save images in a MySQL database and display them later on.

Setting up the database

The difference between any regular text or integer fields and a field that
needs to save an image is the amount of data that is needed to be held in the
field. MySQL uses special fields to hold large amounts of data. These fields
are known as blobs (blob).

Here is the BLOB definition from the MySQL site :

A BLOB is a binary large object that can hold a variable amount of data. The
four BLOB types TINYBLOB, BLOB, MEDIUMBLOB and LONGBLOB differ only in the
maximum length of the values they can hold

For more information about MySQL BLOBs check out
hapter/manual_Reference.html#BLOB

Use the next syntax to create a basic table that will hold the images:

CREATE TABLE Images (
PicNum int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Image BLOB
);

Setting the upload script

An example of a file upload front end can be seen at File Uploading by berber
(29/06/99). What we need now is the PHP script that will get the file and
insert it into MySQL. The next script does just that. In the script, I'm
assuming that the name of the file field is "icture".

<?
If($Picture != "none") {
$PSize = filesize($Picture);
$mysqlPicture = addslashes(fread(fopen($Picture, "r"), $PSize));
unlink($Picture);
mysql_connect($host,$username,$password)
or die("Unable to connect to SQL server");
@mysql_select_db($db)
or die("Unable to select database");
mysql_query("INSERT INTO Images (Image) VALUES '($mysqlPicture')")
or die("Can't Perform Query");
}
else {
echo"You did not upload any picture";
}
?>

This is all that is needed to enter the image into the database. Note that in
some cases you might get an error when you try to insert the image into
MySQL. In such a case you should check the maximum packet size allowed by
your MySQL ver. It might be too small and you will see an error about this in
the MySQL error log.

What we did in the above file is :

1. Check if a file was uploaded with If($Picture != "none").
2. addslashes() to the picture stream to avoide errors in MySQL.
3. Delete the temporary file.
3. Connect to MySQL, choose the database and insert the image.

Displaying the Images

Now that we know how to get the images into the database we need to figure
out how to get them out and display them. This is more complicated than
getting them in but if you follow these steps you will have this up and
running in no time.

Since showing a picture requires a header to be sent, we seem to be in an
impossible situation in which we can only show one picture and than we can't
show anymore Since once the headers are sent we can't send any more headers.

This is the tricky part. To outsmart the system we use two files. The first
file is the HTML template that knows where we want to display the image(s).
It's a regular PHP file, which builds the HTML that contains the <IMG> tags,
as we want to display them. The second file is called to provide the actual
file stream from the database directly into the SRC property of the <IMG>
tag.

This is how a simple script of the first type should look like:

<HTML>
<BODY>
<?
mysql_connect($host,$username,$password)
or die("Unable to connect to SQL server");
@mysql_select_db($db)
or die("Unable to select database");
mysql_query("SELECT * FROM Images")
or die("Can't Perform Query");
While($row=mysql_fetch_object($result)) {
echo "<IMG SRC=\"SecondType.php3?PicNum=$row->icNum\">";
}
?>
</BODY>
</HTML>

While the HTML is being displayed, the SecondType.php3 file is called for
each image we want to display. The script is called with the Picture ID
(PicNum) which allows us to fetch the image and display it.

The SecondType.php3 file looks like this :

<?
$result=mysql_query("SELECT * FROM Images WHERE PicNum=$PicNum")
or die("Can't perform Query");
$row=mysql_fetch_object($result);
Header( "Content-type: image/gif");
echo $row->Image;
?>

This is the whole theory behind images and MySQL. The scripts in this example
are the basics. You can now enhance these scripts to include thumbnails, set
the images in various positions, enhance the database table to hold an ALT
field, Check the width and height of the images before you insert them into
the database and keep that data in the table too etc...

⑦ c#如何把图片变二进制的数据,保存起来,写入文件中。

//---path 图片的地址
FileStream fs = new FileStream(path, FileMode.Open);
// 使用文件流构造一个二进制读取器将基元数据读作二进制值
BinaryReader br = new BinaryReader(fs);
byte[] imageBuffer = new byte[br.BaseStream.Length];
br.Read(imageBuffer, 0, Convert.ToInt32(br.BaseStream.Length));
string textString = System.Convert.ToBase64String(imageBuffer);
fs.Close();
br.Close();
//------textString 就是二进制 图片的字符串了

⑧ 如何在mssql中二进制储存图片

1.将图片以二进制存入数据库
//保存图片到数据库
protected void Button1_Click(object sender, EventArgs e)
{
//图片路径
string strPath = "~/photo/03.JPG";
string strPhotoPath = Server.MapPath(strPath);
//读取图片
FileStream fs = new System.IO.FileStream(strPhotoPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
//存入
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " INSERT INTO personPhoto(personName, personPhotoPath, personPhoto) ";
strComm += " VALUES('wangwu', '" + strPath + "', @photoBinary )";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary,photo.Length);
myComm.Parameters["@photoBinary"].Value = photo;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
}
2.读取二进制图片在页面显示
//读取图片
SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
string strComm = " SELECT personPhoto FROM personPhoto WHERE personName='wangwu' ";
SqlCommand myComm = new SqlCommand(strComm, myConn);
myConn.Open();
SqlDataReader dr = myComm.ExecuteReader();
while (dr.Read())
{
byte[] photo = (byte[])dr["personPhoto"];
this.Response.BinaryWrite(photo);
}
dr.Close();
myConn.Close();

SqlConnection myConn = new SqlConnection("Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
this.Response.BinaryWrite(photo);
3.设置Image控件显示从数据库中读出的二进制图片
---------------------------------------------
SqlConnection myConn = new SqlConnection("Data Source=192.168.0.1;Initial Catalog=TestDB;User ID=sa;Password=sa");
SqlDataAdapter myda = new SqlDataAdapter(" SELECT personPhoto FROM personPhoto WHERE personName='11' ", myConn);
DataSet myds = new DataSet();
myConn.Open();
myda.Fill(myds);
myConn.Close();
byte[] photo = (byte[])myds.Tables[0].Rows[0]["personPhoto"];
//图片路径
string strPath = "~/photo/wangwu.JPG";
string strPhotoPath = Server.MapPath(strPath);
//保存图片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));
bw.Write(photo);
bw.Close();
3.显示图片
this.Image1.ImageUrl = strPath;
4.GridView中ImageField以URL方式显示图片
--------------------------
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="personName" HeaderText="姓名" />
<asp:ImageField DataImageUrlField="personPhotoPath"
HeaderText="图片">
</asp:ImageField>
</Columns>
</asp:GridView>
5.GridView显示读出的二进制图片
//样板列
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="personName" HeaderText="姓名" />
<asp:ImageField DataImageUrlField="personPhotoPath"
HeaderText="图片">
</asp:ImageField>
<asp:TemplateField HeaderText="图片">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex < 0)
return;
// System.ComponentModel.Container
string strPersonName = (string)DataBinder.Eval(e.Row.DataItem, "personName");
Image tmp_Image = (Image)e.Row.Cells[2].FindControl("Image1");
if (!System.Convert.IsDBNull(DataBinder.Eval(e.Row.DataItem, "personPhoto")))
{
//
byte[] photo = (byte[])DataBinder.Eval(e.Row.DataItem, "personPhoto");
//图片路径
string strPath = "~/photo/" + strPersonName.Trim() + ".JPG";
string strPhotoPath = Server.MapPath(strPath);
//保存图片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath, FileMode.OpenOrCreate));
bw.Write(photo);
bw.Close();
//显示图片
tmp_Image.ImageUrl = strPath;
}
}

⑨ 如何将图片转换成二进制存储

资源简介图片的常见存储与读取凡是有以下几种:存储图片:以二进制的形式存储图片时,要把数据库中的字段设置为Image数据类型(SQL Server),存储的数据是Byte[].1.参数是图片路径:返回Byte[]类型: public byte[] GetPictureData(string imagepath) { /**/////根据图片文件的路径使用文件流打开,并保存为byte[] FileStream fs = new FileStream(imagepath, FileMode.Open);//可以是其他重载方法 byte[] byData = new byte[fs.Length]; fs.Read(byData, 0, byData.Length); fs.Close(); return byData; }2.参数类型是Image对象,返回Byte[]类型: public byte[] PhotoImageInsert(System.Drawing.Image imgPhoto) { //将Image转换成流数据,并保存为byte[] MemoryStream mstream = new MemoryStream(); imgPhoto.Save(mstream, System.Drawing.Imaging.ImageFormat.Bmp); byte[] byData = new Byte[mstream.Length]; mstream.Position = 0; mstream.Read(byData, 0, byData.Length); mstream.Close(); return byData; }好了,这样通过上面的方法就可以把图片转换成Byte[]对象,然后就把这个对象保存到数据库中去就实现了把图片的二进制格式保存到数据库中去了。下面我就谈谈如何把数据库中的图片读取出来,实际上这是一个相反的过程。读取图片:把相应的字段转换成Byte[]即:Byte[] bt=(Byte[])XXXX1.参数是Byte[]类型,返回值是Image对象: public System.Drawing.Image ReturnPhoto(byte[] streamByte) { System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte); System.Drawing.Image img = System.Drawing.Image.FromStream(ms); return img; }2.参数是Byte[] 类型,没有返回值,这是针对asp.net中把图片从输出到网页上(Response.BinaryWrite) public void WritePhoto(byte[] streamByte) { // Response.ContentType 的默认值为默认值为“text/html” Response.ContentType = "image/GIF"; //图片输出的类型有: image/GIF image/JPEG Response.BinaryWrite(streamByte); }补充:针对Response.ContentType的值,除了针对图片的类型外,还有其他的类型: Response.ContentType = "application/msword"; Response.ContentType = "application/x-shockwave-flash"; Response.ContentType = "application/vnd.ms-excel";另外可以针对不同的格式,用不同的输出类型以适合不同的类型: switch (dataread("document_type")) { case "doc": Response.ContentType = "application/msword"; case "swf": Response.ContentType = "application/x-shockwave-flash"; case "xls": Response.ContentType = "application/vnd.ms-excel"; case "gif": Response.ContentType = "image/gif"; case "Jpg": Response.ContentType = "image/jpeg"; }立即获得您的.

⑩ 图片如何存入数据库

通常对用户上传的图片需要保存到数据库中。解决方法一般有两种:一种是将图片保存的路径存储到数据库;另一种是将图片以二进制数据流的形式直接写入数据库字段中。以下为具体方法:
一、保存图片的上传路径到数据库:
string uppath="";//用于保存图片上传路径
//获取上传图片的文件名
string fileFullname = this.FileUpload1.FileName;
//获取图片上传的时间,以时间作为图片的名字可以防止图片重名
string dataName = DateTime.Now.ToString("yyyyMMddhhmmss");
//获取图片的文件名(不含扩展名)
string fileName = fileFullname.Substring(fileFullname.LastIndexOf("\\") + 1);
//获取图片扩展名
string type = fileFullname.Substring(fileFullname.LastIndexOf(".") + 1);
//判断是否为要求的格式
if (type == "bmp" || type == "jpg" || type == "jpeg" || type == "gif" || type == "JPG" || type == "JPEG" || type == "BMP" || type == "GIF")
{
//将图片上传到指定路径的文件夹
this.FileUpload1.SaveAs(Server.MapPath("~/upload") + "\\" + dataName + "." + type);
//将路径保存到变量,将该变量的值保存到数据库相应字段即可
uppath = "~/upload/" + dataName + "." + type;
}
二、将图片以二进制数据流直接保存到数据库:
引用如下命名空间:
using System.Drawing;
using System.IO;
using System.Data.SqlClient;
设计数据库时,表中相应的字段类型为iamge
保存:
//图片路径
string strPath = this.FileUpload1.PostedFile.FileName.ToString ();
//读取图片
FileStream fs = new System.IO.FileStream(strPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
//存入
SqlConnection myConn = new SqlConnection("Data Source=.;Initial Catalog=stumanage;User ID=sa;Password=123");
string strComm = " INSERT INTO stuInfo(stuid,stuimage) VALUES(107,@photoBinary )";//操作数据库语句根据需要修改
SqlCommand myComm = new SqlCommand(strComm, myConn);
myComm.Parameters.Add("@photoBinary", SqlDbType.Binary, photo.Length);
myComm.Parameters["@photoBinary"].Value = photo;
myConn.Open();
if (myComm.ExecuteNonQuery() > 0)
{
this.Label1.Text = "ok";
}
myConn.Close();
读取:
...连接数据库字符串省略
mycon.Open();
SqlCommand command = new
SqlCommand("select stuimage from stuInfo where stuid=107", mycon);//查询语句根据需要修改
byte[] image = (byte[])command.ExecuteScalar ();
//指定从数据库读取出来的图片的保存路径及名字
string strPath = "~/Upload/zhangsan.JPG";
string strPhotoPath = Server.MapPath(strPath);
//按上面的路径与名字保存图片文件
BinaryWriter bw = new BinaryWriter(File.Open(strPhotoPath,FileMode.OpenOrCreate));
bw.Write(image);
bw.Close();
//显示图片
this.Image1.ImageUrl = strPath;
采用俩种方式可以根据实际需求灵活选择。