?
Solved

Unable to convert byte to bitmap

Posted on 2013-06-19
7
Medium Priority
?
438 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
Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

 
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

Moving data to the cloud? Find out if you’re ready

Before moving to the cloud, it is important to carefully define your db needs, plan for the migration & understand prod. environment. This wp explains how to define what you need from a cloud provider, plan for the migration & what putting a cloud solution into practice entails.

Question has a verified solution.

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

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.
Suggested Courses

649 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