我將許多 JPEG 影像作為 Long 二進制資料添加到 Access DB 中。現在我想將這些影像檢索到TImage使用 Delphi 代碼中。
對于這項作業,我撰寫了下面的代碼,但運行后它給了我一個JPEG 錯誤 #53錯誤。我在谷歌中搜索了這個錯誤代碼,并嘗試了一些解決方案,例如將圖片另存為新的 JPG 格式,但這并沒有改變任何東西。
此外,我發現了從資料庫中檢索影像的不同代碼,但它們都給了我相同的JPEG 錯誤 #53錯誤。
哪里有問題?
procedure RetrieveImage;
var
Jpg : TGraphic;
Stream: TStream;
query : string;
Field: TBlobField;
Begin
Stream := nil;
Jpg := nil;
query := 'Select JPGFile From Table Where Name=' QuotedStr(SoftName);
Try
With ADOQuery do
Begin
Try
SQL.Clear;
SQL.Add(query);
Open;
Field := TBlobField(FieldbyName('JPGFile'));
Stream := CreateBlobStream(Field,bmRead);
Jpg := TJpegImage.Create;
Jpg.LoadFromStream(Stream);
MainForm.PictureBox.Picture.Graphic:= Jpg;
Finally
Close;
End;
End;
Finally
Stream.Free;
Jpg.Free;
End;
End;
編輯:
我使用 C# 代碼將 JPG 檔案插入資料庫(以下代碼已簡化):
// Insert Data to Access tables
private void InsertToTable(string connectionString, string query)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
try
{
connection.Close();
using (OleDbCommand command = new OleDbCommand(query, connection))
{
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
reader.Close();
}
command.Cancel();
}
connection.Close();
}
finally
{
connection.Close();
}
}
}
// Insert Image into database
private void SaveToDataBase(string jpegPath)
{
//jpegPath example is: (C:\Image\1.jpg)
string FilePath = Application.StartupPath directory dbName;
string MDBConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" FilePath "; Jet OLEDB:Engine Type=5";
// Convert Image to binary
var image = File.ReadAllBytes(jpegPath);
InsertToTable(MDBConnStr, $"INSERT INTO Table JPGFile VALUES('{image}')");
}
uj5u.com熱心網友回復:
在您的 C# 代碼中,為什么要使用ExecuteReader()來執行INSERT陳述句?你應該ExecuteNonQuery()改用。
更重要的是,您實際上并沒有將image位元組陣列的內容插入資料庫,這就是 DelphiTJPEGImage稍后無法加載資料的原因。您的 SQL 查詢被創建為插值字串,但您的{image}運算式不會像您認為的那樣將原始位元組插入查詢中。即使這樣做,這也不是將原始位元組插入“長二進制”欄位開始的正確方法。
您需要改用引數化查詢。OleDbParameter向command.Parameters集合中添加一個以將image資料傳遞到資料庫中,在其中將其DbType屬性設定為Binary,將其OleDbType屬性設定為Binary、LongVarBinary或VarBinary,并將其Value屬性設定為image位元組陣列。然后,您可以在 SQL 陳述句中參考該引數。
請參閱配置引數和引數資料型別,尤其是使用 OleDbCommand 或 OdbcCommand 的引數部分。
嘗試更多類似的東西:
// Insert Image into database
private void SaveToDataBase(string jpegPath)
{
//jpegPath example is: (C:\Image\1.jpg)
// Convert Image to binary
var image = File.ReadAllBytes(jpegPath);
string FilePath = Application.StartupPath directory dbName;
string MDBConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;" "Data Source=" FilePath "; Jet OLEDB:Engine Type=5";
using (OleDbConnection connection = new OleDbConnection(MDBConnStr))
{
connection.Open();
using (OleDbCommand command = new OleDbCommand("INSERT INTO Table JPGFile VALUES(?)", connection))
{
command.Parameters.Add("@Image", OleDbType.LongVarBinary).Value = image;
command.ExecuteNonQuery();
}
}
}
但是請注意,OLEDB 中的二進制引數最大限制為 8000 位元組。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/471640.html
上一篇:更改所有對話框的整個字體樣式
