Solved

Unable to convert byte to bitmap

Posted on 2013-06-19
7
425 Views
Last Modified: 2013-08-20
I have a sql server table named "DOCUVALUE" with a column named "FILE_" which is of type IMAGE.  I am using the following code to try to convert the jpegs stored in that column to bitmaps so that I can resize them.  I am able to read the files and put them into a memory stream, but when I try to create the bitmap, or an image, I get the error "Parameter is invalid."  This happens with every record I try, so I know that it is not a data type problem.  These are images that were uploaded from our web site.  Can someone tell me what I am doing wrong in this code?

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />
        <br />
   
    </div>
    </form>
</body>
</html>

Code behind:

Imports System.IO
Imports System.Drawing
Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click

        Dim conn As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand
        Dim reader As SqlClient.SqlDataReader

        'again the connection string for the database that contains the images
        conn.ConnectionString = Helper.GetConnectionString
        conn.Open()
        cmd = conn.CreateCommand()

        'query that retrieves a single image on basis of the passed id
        cmd.CommandText = "SELECT FILE_ FROM DBO.DOCUVALUE WHERE RECID = 5637654152"
        reader = cmd.ExecuteReader

        If reader.Read Then

            Dim imgByteArray() As Byte

            Try

                'read the image as a stream and make a bitmap out of it
                imgByteArray = CType(reader(0), Byte())

                Dim stream As New MemoryStream(imgByteArray)

                Dim bmp As New Bitmap(stream)

                'Dim img As Image = Image.FromStream(stream)

            Catch ex As Exception

            End Try

        End If 'reader.Read

    End Sub

End Class

Helper class:
Imports Microsoft.VisualBasic
Imports System.Web.Configuration
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Data
Imports System.Reflection

Partial Public Class Helper


    Public Shared Function GetConnectionString() As String

        ' Return WebConfigurationManager.ConnectionStrings("HRV_SQL_Dev").ConnectionString
        Return WebConfigurationManager.ConnectionStrings("HRV_SQL_Test").ConnectionString
        ' Return WebConfigurationManager.ConnectionStrings("HRV_Dev1").ConnectionString

    End Function

End Class

Web.config:

<?xml version="1.0"?>

<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="HRV_SQL_Dev" connectionString="Data Source=hrvsqltest;Initial Catalog=AX40SP2Dev;Max Pool Size=10;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    <add name="HRV_SQL_Test" connectionString="Data Source=hrvsqltest;Initial Catalog=AX40SP2Test;Max Pool Size=10;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    <add name="HRV_SQL_Live" connectionString="Data Source=hrvaxdb2;Initial Catalog=AX40SP2Live;Max Pool Size=500;Integrated Security=True;" providerName="System.Data.SqlClient"/>
    <add name="HRV_Dev1" connectionString="Data Source=hrvsqltest;Initial Catalog=HRV_Dev1;Max Pool Size=500;Integrated Security=True;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <system.web>

    <compilation debug="true" strict="false" explicit="true" targetFramework="4.0">

      <assemblies>
        <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.DirectoryServices, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>

    </compilation>

  </system.web>

</configuration>
0
Comment
Question by:tdisher
  • 3
  • 3
7 Comments
 
LVL 23

Expert Comment

by:nemws1
ID: 39261013
The last time I tried something similar, there were 2-4 extra bytes that somehow got injected at the *beginning* of the file.  Any change you know how to use a binary editor and can look/post the first 20-30 bytes of this file?

Here are the first whatever bytes from several random JPG files I had on my filesystem:
FF
D8
FF
EO
NULL
^P
J
F
I
F
NULL
^A
^A
^A
0
 
LVL 13

Expert Comment

by:Molnar István
ID: 39263424
you could try like this:
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(byteArray);
or with this:
public static Bitmap BytesToBitmap(byte[] byteArray)
{
using (MemoryStream ms = new MemoryStream(byteArray))
{
Bitmap img = (Bitmap)Image.FromStream(ms);
return img;
}
}

reference: http://social.msdn.microsoft.com/Forums/windows/en-US/e57f7731-c703-4c17-b1a2-32b155f9b745/how-to-convert-byte-array-to-bitmap-in-c

Hope it helps
0
 

Author Comment

by:tdisher
ID: 39265745
Which binary editor should I use to get the results you are wanting to see?
0
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 23

Expert Comment

by:nemws1
ID: 39271649
I like this one:

http://www.chmaas.handshake.de/delphi/freeware/xvi32/xvi32.htm

Attached in an image from a JPEG file so you can see what the first bytes of the file *should* look like.
HEX dump of JPEG file
0
 
LVL 23

Expert Comment

by:nemws1
ID: 39275150
Have you had a chance to see if you're extracting valid images from the database yet?
0
 

Accepted Solution

by:
tdisher earned 0 total points
ID: 39411059
Nothing ever worked on this...
0
 

Author Closing Comment

by:tdisher
ID: 39422718
No expert suggestion worked.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

816 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now