首页 > 解决方案 > Asp.net core 3.0中的字节[]到图像转换

问题描述

我正在开发 Asp.net core 3.0 API 服务。我必须在 sql server 中将图像存储为 byte[] 格式。当我保存图像时,我已经完成了。但问题是从服务器检索它。

在这里,我所做的示例代码是,

API 控制器,

    [HttpGet("GetEmployeeDetails")]
    public async Task<IActionResult> GetEmployeeDetails()
    {
        try
        {
               var employeesList = await _employeePhoto.GetEmployeeDetails();
            if (employeesList == null)
                return NoContent();
            else
            {
                var finalResultList = new List<GetEmployeePhotoResultEntity>();
                for (int i = 0; i <= employeesList.Count; i++)
                {
                    var EmployeePhoto = System.Text.Encoding.Unicode.GetBytes(employeesList[i].Employee_Photo);
                    finalResultList[i].Employee_Id = employeesList[i].Employee_Id;
                    finalResultList[i].Employee_Code = employeesList[i].Employee_Code;
                    finalResultList[i].Employee_Name = employeesList[i].Employee_Name;
                    finalResultList[i].Employee_Photo = File(EmployeePhoto, "image/jpeg");
                }
                return Ok(finalResultList);
            }
        }
        catch (Exception exception)
        {
            _logger.LogError($"EmployeePhotoController {exception.InnerException.Message.ToString()}");
            return StatusCode(StatusCodes.Status500InternalServerError, exception.InnerException.Message);
        }

服务 :

    public async Task<List<GetEmployeePhotoEntity>> GetEmployeeDetails()
    {
        try
        {
            DataTable dataTable = await _dbRepository.GetDataTable("sp_EmployeesPhoto_Select");
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                return (from DataRow dr in dataTable.Rows
                        select new GetEmployeePhotoEntity()
                        {
                            Employee_Id = Convert.ToInt32(dr["Employee_Id"]?.ToString()),
                            Employee_Code = dr["Employee_Code"]?.ToString(),
                            Employee_Name = dr["Employee_Name"]?.ToString(),
                            Employee_Photo = dr["Employee_Photo"]?.ToString()
                        }).ToList();
            }
            else
                return null;

        }
        catch (Exception exception)
        {
            _logger.LogError($"@@@EmployeePhotoService {exception.InnerException.ToString()}");
            throw;
        }
    }

和实体,

public class GetEmployeePhotoEntity
{
    public int Employee_Id { get; set; }
    public string Employee_Code { get; set; }
    public string Employee_Name { get; set; }
    public string Employee_Photo { get; set; }
}
public class GetEmployeePhotoResultEntity
{
    public int Employee_Id { get; set; }
    public string Employee_Code { get; set; }
    public string Employee_Name { get; set; }
    public FileContentResult Employee_Photo { get; set; }
}

和表结构,Employee_Photos table Employee_Id int Photo image

而且,我的 UI 是 Angular 8,在 Angular 中,我在 Mat-Table 中展示了如何将它们绑定到 Angular 中。请尽快回答任何人

标签: asp.net-coreasp.net-core-3.0

解决方案


当我尝试@Nan Yu 给出的建议时的输出

我的 Angular ts 服务是,

public getEmployeeDetailsList(): void {
debugger;
this._httpClient.get(this.API_URL + 'EmployeePhoto/GetEmployeeDetails/').subscribe(
  (result: any) => {
    console.log(result);
    let employeesList = result;
    for(let i=0; i < result.length;i++) {
      let imageBinary = result[i].Employee_Photo; //image binary data response from api
      let imageBase64String = btoa(imageBinary);
      employeesList[i].Employee_Photo = imageBase64String
    }

    console.log(employeesList, "Converted Employees List")
    this.dataSource = employeesList;
  });

}

而 HTML 是,

                                    <ng-container matColumnDef="Travel_Indent_No" sticky>
                                        <mat-header-cell *matHeaderCellDef>
                                            Employee Photo
                                        </mat-header-cell>
                                        <mat-cell *matCellDef="let element" class="row-no">
                                            <img style="text-align:center;border:1px solid white" type="file"
                                                height="100px" width="100px" src="data:image/JPEG;base64,{{element.Employee_Photo}}" />
                                        </mat-cell>
                                    </ng-container>

以及为 Employee_Photo 返回以下字节 [] 的 API 控制器

    public async Task<IActionResult> GetEmployeeDetails()
    {
        try
        {
               List<GetEmployeePhotoEntity> employeesList = await _employeePhoto.GetEmployeeDetails();
            if (employeesList != null)
                return Ok(employeesList);
            else
            {
                return NoContent();
            }
        }
        catch (Exception exception)
        {
            _logger.LogError($"EmployeePhotoController {exception.InnerException.Message.ToString()}");
            return StatusCode(StatusCodes.Status500InternalServerError, exception.InnerException.Message);
        }
    }

GetEmployeePhotoEntity 是

public class GetEmployeePhotoEntity
{
    public int Employee_Id { get; set; }
    public string Employee_Code { get; set; }
    public string Employee_Name { get; set; }
    public byte[] Employee_Photo { get; set; }
}

推荐阅读