?
Solved

Unable to convert byte to bitmap

Posted on 2013-06-19
7
Medium Priority
?
434 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

 
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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

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

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
In the first part of this tutorial we will cover the prerequisites for installing SQL Server vNext on Linux.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
Suggested Courses

762 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