且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像存储在数据库中会产生部分图像

更新时间:2023-02-24 08:31:01

p>

将imagedata映射更改为

Map(x => x.Data).Column(ImageData)。 CustomSqlType(VARBINARY(MAX))。Length(160000);

由于某些原因,通过nhibernate映射将数据截断为8000字节。添加这个固定它。


I'm trying to store images in a sql server database. I've got a column in an Image table which stores the data and is of type varbinary(max). I'm using NHibernate to access the database.

The loading of the image into the code and converting it to a buffer array works fine. When I store the image in the database, no matter what size image above 30kb that I put in, only part of the image is saved.

I checked the data stored in the database and all images have the same amount of data stored so my guess is that something is limiting the size of the byte[] that can be held in the column.

When I pull the data out of the database and display the image on the screen, it shows the top portion of the image only.

What could be wrong?

Update: I checked the size of the data in the varbinary(max) column and all data entries are 8000bytes.

Here's the code:

Table Creation:

IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE 'Image')
            CREATE TABLE [Image]
            (
                [ImageId]                       INT IDENTITY(1,1)       NOT NULL,
                [FileName]                      NVARCHAR(MAX)           NOT NULL,
                [ImageData]                     VARBINARY(MAX)          NOT NULL,
                [Caption]                       NVARCHAR(MAX)           NULL,
                CONSTRAINT PK_ImageId PRIMARY KEY CLUSTERED (ImageId ASC)
                ON [PRIMARY]
            )

Fluent mapping:

public ImageMap()
    {
        Id(x=>x.Id,"ImageId").GeneratedBy.Identity();
        Map(x => x.Caption);
        Map(x => x.FileName);
        Map(x => x.Data).Column("ImageData");
        HasMany(x => x.ArticleImages).KeyColumn("ImageId").Inverse();
        HasOne(x => x.Thumbnail).PropertyRef(r=>r.Image).Cascade.All();
    }

NHibernate entity class:

using System.Collections.Generic;


public class Image : BaseEntity
{
    /// <summary>
    /// Image's name
    /// </summary>
    public virtual string FileName { get; set; }

    /// <summary>
    /// Image's Caption
    /// </summary>
    public virtual string Caption { get; set; }

    /// <summary>
    /// Binary data for the image
    /// </summary>
    public virtual byte[] Data { get; set; }

    /// <summary>
    /// Link to article
    /// </summary>
    public virtual IEnumerable<ArticleImage> ArticleImages { get; set; }

    /// <summary>
    /// The thumbnail for the image
    /// </summary>
    public virtual ImageThumbnail Thumbnail { get; set; }
}

Fixed it.

Changed the imagedata mapping to

Map(x => x.Data).Column("ImageData").CustomSqlType("VARBINARY(MAX)").Length(160000);

For some reason, the data was being truncated to 8000 bytes via the nhibernate mapping. Adding this fixed it.