① 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文字識別工具。
方法:
運行ocr文字識別工具,選擇上面功能欄中的「極速識別」功能。
點擊左上角的「添加文件」,把需要轉換的圖片文字添加進去。
在上面選擇文件的「識別格式」。
點擊操作下面的「開始識別」按鈕。
希望上面的方法可以幫助到你哦!
④ 如何將文本中的二進制數據保存為一個文件
不知道你是不是想問的這個,可以參考一下
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;
採用倆種方式可以根據實際需求靈活選擇。