Can't convert SQL VARBINARY to byte[] correctly and convert to Image in ASP.NET c#2019 Community Moderator ElectionConvert a string to an enum in C#How do you convert a byte array to a hexadecimal string, and vice versa?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to convert UTF-8 byte[] to string?How to convert an Stream into a byte[] in C#?SqlDataReader C#, SQL Server 2005, VS 2008How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?How convert byte array to stringConverting string to byte array in C#How to convert Java String into byte[]?

What happens when the centripetal force is equal and opposite to the centrifugal force?

Is this Pascal's Matrix?

Do I need an EFI partition for each 18.04 ubuntu I have on my HD?

How to determine the greatest d orbital splitting?

Did Nintendo change its mind about 68000 SNES?

Should I be concerned about student access to a test bank?

Homology of the fiber

Was World War I a war of liberals against authoritarians?

Could any one tell what PN is this Chip? Thanks~

Friend wants my recommendation but I don't want to give it to him

Why is this tree refusing to shed its dead leaves?

Help with identifying unique aircraft over NE Pennsylvania

label a part of commutative diagram

Gauss brackets with double vertical lines

Why I don't get the wanted width of tcbox?

Are hand made posters acceptable in Academia?

Imaginary part of expression too difficult to calculate

How to balance a monster modification (zombie)?

UK Tourist Visa- Enquiry

What kind of footwear is suitable for walking in micro gravity environment?

Would this string work as string?

Is xar preinstalled on macOS?

Asserting that Atheism and Theism are both faith based positions

How do researchers send unsolicited emails asking for feedback on their works?



Can't convert SQL VARBINARY to byte[] correctly and convert to Image in ASP.NET c#



2019 Community Moderator ElectionConvert a string to an enum in C#How do you convert a byte array to a hexadecimal string, and vice versa?How do I get a consistent byte representation of strings in C# without manually specifying an encoding?How to convert UTF-8 byte[] to string?How to convert an Stream into a byte[] in C#?SqlDataReader C#, SQL Server 2005, VS 2008How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?How convert byte array to stringConverting string to byte array in C#How to convert Java String into byte[]?










0















Here is what I'm doing:



public static MVC_Picture GetPictureRecord(int pictureID)

int pictureId = pictureID;
MVC_Picture _picture = new MVC_Picture(); //object that stores name and array

var connString = db.connString;
string cmdText = "SELECT PictureName, PictureImage FROM Picture WHERE CONVERT(INT, ID) =@pictureId;";
using (var connection = new SqlConnection(connString))

using (var sqlCmd = new SqlCommand(cmdText, connection))

SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@pictureId";
param1.Value = pictureId;
sqlCmd.Parameters.Add(param1);

connection.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
while (dr.Read())

_picture.Id = pictureId;
_picture.PictureName = Convert.ToString(dr["PictureName"]);
_picture.PictureImage = (byte[])(dr["PictureImage"]); //Problem

connection.Close();



return _picture;



When I convert to byte[] I get something like: byte[4354567]



I'm then trying to convert array to Image like so:



Image img = (Image)converter.ConvertFrom(_picture.PictureImage);
ViewModel.FeaturedImage = img;


And in View I use:



<img src="@ViewModel.FeaturedImage" alt="Featured Image" />


What am I missing?










share|improve this question




























    0















    Here is what I'm doing:



    public static MVC_Picture GetPictureRecord(int pictureID)

    int pictureId = pictureID;
    MVC_Picture _picture = new MVC_Picture(); //object that stores name and array

    var connString = db.connString;
    string cmdText = "SELECT PictureName, PictureImage FROM Picture WHERE CONVERT(INT, ID) =@pictureId;";
    using (var connection = new SqlConnection(connString))

    using (var sqlCmd = new SqlCommand(cmdText, connection))

    SqlParameter param1 = new SqlParameter();
    param1.ParameterName = "@pictureId";
    param1.Value = pictureId;
    sqlCmd.Parameters.Add(param1);

    connection.Open();
    SqlDataReader dr = sqlCmd.ExecuteReader();
    while (dr.Read())

    _picture.Id = pictureId;
    _picture.PictureName = Convert.ToString(dr["PictureName"]);
    _picture.PictureImage = (byte[])(dr["PictureImage"]); //Problem

    connection.Close();



    return _picture;



    When I convert to byte[] I get something like: byte[4354567]



    I'm then trying to convert array to Image like so:



    Image img = (Image)converter.ConvertFrom(_picture.PictureImage);
    ViewModel.FeaturedImage = img;


    And in View I use:



    <img src="@ViewModel.FeaturedImage" alt="Featured Image" />


    What am I missing?










    share|improve this question


























      0












      0








      0








      Here is what I'm doing:



      public static MVC_Picture GetPictureRecord(int pictureID)

      int pictureId = pictureID;
      MVC_Picture _picture = new MVC_Picture(); //object that stores name and array

      var connString = db.connString;
      string cmdText = "SELECT PictureName, PictureImage FROM Picture WHERE CONVERT(INT, ID) =@pictureId;";
      using (var connection = new SqlConnection(connString))

      using (var sqlCmd = new SqlCommand(cmdText, connection))

      SqlParameter param1 = new SqlParameter();
      param1.ParameterName = "@pictureId";
      param1.Value = pictureId;
      sqlCmd.Parameters.Add(param1);

      connection.Open();
      SqlDataReader dr = sqlCmd.ExecuteReader();
      while (dr.Read())

      _picture.Id = pictureId;
      _picture.PictureName = Convert.ToString(dr["PictureName"]);
      _picture.PictureImage = (byte[])(dr["PictureImage"]); //Problem

      connection.Close();



      return _picture;



      When I convert to byte[] I get something like: byte[4354567]



      I'm then trying to convert array to Image like so:



      Image img = (Image)converter.ConvertFrom(_picture.PictureImage);
      ViewModel.FeaturedImage = img;


      And in View I use:



      <img src="@ViewModel.FeaturedImage" alt="Featured Image" />


      What am I missing?










      share|improve this question
















      Here is what I'm doing:



      public static MVC_Picture GetPictureRecord(int pictureID)

      int pictureId = pictureID;
      MVC_Picture _picture = new MVC_Picture(); //object that stores name and array

      var connString = db.connString;
      string cmdText = "SELECT PictureName, PictureImage FROM Picture WHERE CONVERT(INT, ID) =@pictureId;";
      using (var connection = new SqlConnection(connString))

      using (var sqlCmd = new SqlCommand(cmdText, connection))

      SqlParameter param1 = new SqlParameter();
      param1.ParameterName = "@pictureId";
      param1.Value = pictureId;
      sqlCmd.Parameters.Add(param1);

      connection.Open();
      SqlDataReader dr = sqlCmd.ExecuteReader();
      while (dr.Read())

      _picture.Id = pictureId;
      _picture.PictureName = Convert.ToString(dr["PictureName"]);
      _picture.PictureImage = (byte[])(dr["PictureImage"]); //Problem

      connection.Close();



      return _picture;



      When I convert to byte[] I get something like: byte[4354567]



      I'm then trying to convert array to Image like so:



      Image img = (Image)converter.ConvertFrom(_picture.PictureImage);
      ViewModel.FeaturedImage = img;


      And in View I use:



      <img src="@ViewModel.FeaturedImage" alt="Featured Image" />


      What am I missing?







      c# sql arrays image-processing






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 7 at 19:13









      Lews Therin

      2,69911640




      2,69911640










      asked Mar 7 at 19:11









      positive perspectivepositive perspective

      12010




      12010






















          1 Answer
          1






          active

          oldest

          votes


















          0














          <img src=... has to point to an image file by its path, eg <img src="/myImage.jpg">. You can't stick a binary representation of the image in the src and have it work.



          So you could either write those binary images out to disk somewhere (you probably don't want to do that, as then you're duplicating the data, and would have to manage synchronizing).



          Or you could create some kind of image handler, so the <img src= would be something like: <img src="/myHandler/imageId", and then have the handler read the binary data from the database and respond with the image.



          This is an MVC controller action that I've used in the past to read a binary PDF out of the DB, and return it as a file. This is in my Competition controller. If this was returning an image, you could call it something like:



          <img src="Competition/ViewJobDescription?competitionId=1234" />



           public ActionResult ViewJobDescription(int competitionId)

          string errorMsg = "";
          var competition = new DBModel.Competition();
          try

          competition = DBModel.Competition.GetCompetition(competitionId);
          if (competition != null && competition.AttachmentContent != null)

          byte[] fileData = competition.AttachmentContent;
          string filename = competition.AttachmentTitle + ".pdf";
          return File(fileData, "application/pdf", filename);


          catch (Exception ex)

          errorMsg += "An error occured: " + ex.Message;
          LogFile err = new LogFile();
          err.CreateErrorLog(errorMsg);

          ModelState.AddModelError(string.Empty, errorMsg);


          return RedirectToAction("Index", "Home");






          share|improve this answer

























          • I bind to an actual Image, not binary.

            – positive perspective
            Mar 7 at 19:22











          • No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

            – Jonathan
            Mar 7 at 19:23











          • damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

            – positive perspective
            Mar 7 at 19:24











          • Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

            – Jonathan
            Mar 7 at 19:26











          • ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

            – positive perspective
            Mar 7 at 19:28










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051196%2fcant-convert-sql-varbinary-to-byte-correctly-and-convert-to-image-in-asp-net%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          <img src=... has to point to an image file by its path, eg <img src="/myImage.jpg">. You can't stick a binary representation of the image in the src and have it work.



          So you could either write those binary images out to disk somewhere (you probably don't want to do that, as then you're duplicating the data, and would have to manage synchronizing).



          Or you could create some kind of image handler, so the <img src= would be something like: <img src="/myHandler/imageId", and then have the handler read the binary data from the database and respond with the image.



          This is an MVC controller action that I've used in the past to read a binary PDF out of the DB, and return it as a file. This is in my Competition controller. If this was returning an image, you could call it something like:



          <img src="Competition/ViewJobDescription?competitionId=1234" />



           public ActionResult ViewJobDescription(int competitionId)

          string errorMsg = "";
          var competition = new DBModel.Competition();
          try

          competition = DBModel.Competition.GetCompetition(competitionId);
          if (competition != null && competition.AttachmentContent != null)

          byte[] fileData = competition.AttachmentContent;
          string filename = competition.AttachmentTitle + ".pdf";
          return File(fileData, "application/pdf", filename);


          catch (Exception ex)

          errorMsg += "An error occured: " + ex.Message;
          LogFile err = new LogFile();
          err.CreateErrorLog(errorMsg);

          ModelState.AddModelError(string.Empty, errorMsg);


          return RedirectToAction("Index", "Home");






          share|improve this answer

























          • I bind to an actual Image, not binary.

            – positive perspective
            Mar 7 at 19:22











          • No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

            – Jonathan
            Mar 7 at 19:23











          • damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

            – positive perspective
            Mar 7 at 19:24











          • Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

            – Jonathan
            Mar 7 at 19:26











          • ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

            – positive perspective
            Mar 7 at 19:28















          0














          <img src=... has to point to an image file by its path, eg <img src="/myImage.jpg">. You can't stick a binary representation of the image in the src and have it work.



          So you could either write those binary images out to disk somewhere (you probably don't want to do that, as then you're duplicating the data, and would have to manage synchronizing).



          Or you could create some kind of image handler, so the <img src= would be something like: <img src="/myHandler/imageId", and then have the handler read the binary data from the database and respond with the image.



          This is an MVC controller action that I've used in the past to read a binary PDF out of the DB, and return it as a file. This is in my Competition controller. If this was returning an image, you could call it something like:



          <img src="Competition/ViewJobDescription?competitionId=1234" />



           public ActionResult ViewJobDescription(int competitionId)

          string errorMsg = "";
          var competition = new DBModel.Competition();
          try

          competition = DBModel.Competition.GetCompetition(competitionId);
          if (competition != null && competition.AttachmentContent != null)

          byte[] fileData = competition.AttachmentContent;
          string filename = competition.AttachmentTitle + ".pdf";
          return File(fileData, "application/pdf", filename);


          catch (Exception ex)

          errorMsg += "An error occured: " + ex.Message;
          LogFile err = new LogFile();
          err.CreateErrorLog(errorMsg);

          ModelState.AddModelError(string.Empty, errorMsg);


          return RedirectToAction("Index", "Home");






          share|improve this answer

























          • I bind to an actual Image, not binary.

            – positive perspective
            Mar 7 at 19:22











          • No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

            – Jonathan
            Mar 7 at 19:23











          • damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

            – positive perspective
            Mar 7 at 19:24











          • Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

            – Jonathan
            Mar 7 at 19:26











          • ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

            – positive perspective
            Mar 7 at 19:28













          0












          0








          0







          <img src=... has to point to an image file by its path, eg <img src="/myImage.jpg">. You can't stick a binary representation of the image in the src and have it work.



          So you could either write those binary images out to disk somewhere (you probably don't want to do that, as then you're duplicating the data, and would have to manage synchronizing).



          Or you could create some kind of image handler, so the <img src= would be something like: <img src="/myHandler/imageId", and then have the handler read the binary data from the database and respond with the image.



          This is an MVC controller action that I've used in the past to read a binary PDF out of the DB, and return it as a file. This is in my Competition controller. If this was returning an image, you could call it something like:



          <img src="Competition/ViewJobDescription?competitionId=1234" />



           public ActionResult ViewJobDescription(int competitionId)

          string errorMsg = "";
          var competition = new DBModel.Competition();
          try

          competition = DBModel.Competition.GetCompetition(competitionId);
          if (competition != null && competition.AttachmentContent != null)

          byte[] fileData = competition.AttachmentContent;
          string filename = competition.AttachmentTitle + ".pdf";
          return File(fileData, "application/pdf", filename);


          catch (Exception ex)

          errorMsg += "An error occured: " + ex.Message;
          LogFile err = new LogFile();
          err.CreateErrorLog(errorMsg);

          ModelState.AddModelError(string.Empty, errorMsg);


          return RedirectToAction("Index", "Home");






          share|improve this answer















          <img src=... has to point to an image file by its path, eg <img src="/myImage.jpg">. You can't stick a binary representation of the image in the src and have it work.



          So you could either write those binary images out to disk somewhere (you probably don't want to do that, as then you're duplicating the data, and would have to manage synchronizing).



          Or you could create some kind of image handler, so the <img src= would be something like: <img src="/myHandler/imageId", and then have the handler read the binary data from the database and respond with the image.



          This is an MVC controller action that I've used in the past to read a binary PDF out of the DB, and return it as a file. This is in my Competition controller. If this was returning an image, you could call it something like:



          <img src="Competition/ViewJobDescription?competitionId=1234" />



           public ActionResult ViewJobDescription(int competitionId)

          string errorMsg = "";
          var competition = new DBModel.Competition();
          try

          competition = DBModel.Competition.GetCompetition(competitionId);
          if (competition != null && competition.AttachmentContent != null)

          byte[] fileData = competition.AttachmentContent;
          string filename = competition.AttachmentTitle + ".pdf";
          return File(fileData, "application/pdf", filename);


          catch (Exception ex)

          errorMsg += "An error occured: " + ex.Message;
          LogFile err = new LogFile();
          err.CreateErrorLog(errorMsg);

          ModelState.AddModelError(string.Empty, errorMsg);


          return RedirectToAction("Index", "Home");







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 7 at 19:30

























          answered Mar 7 at 19:20









          JonathanJonathan

          2,86921630




          2,86921630












          • I bind to an actual Image, not binary.

            – positive perspective
            Mar 7 at 19:22











          • No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

            – Jonathan
            Mar 7 at 19:23











          • damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

            – positive perspective
            Mar 7 at 19:24











          • Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

            – Jonathan
            Mar 7 at 19:26











          • ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

            – positive perspective
            Mar 7 at 19:28

















          • I bind to an actual Image, not binary.

            – positive perspective
            Mar 7 at 19:22











          • No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

            – Jonathan
            Mar 7 at 19:23











          • damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

            – positive perspective
            Mar 7 at 19:24











          • Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

            – Jonathan
            Mar 7 at 19:26











          • ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

            – positive perspective
            Mar 7 at 19:28
















          I bind to an actual Image, not binary.

          – positive perspective
          Mar 7 at 19:22





          I bind to an actual Image, not binary.

          – positive perspective
          Mar 7 at 19:22













          No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

          – Jonathan
          Mar 7 at 19:23





          No, an Image is still a binary representation of the image. <img src= requires a path to the image, not the image itself

          – Jonathan
          Mar 7 at 19:23













          damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

          – positive perspective
          Mar 7 at 19:24





          damn. didn't know that. so my array is correct? it's just the reference of img src that is broken?

          – positive perspective
          Mar 7 at 19:24













          Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

          – Jonathan
          Mar 7 at 19:26





          Yes - I'll update my answer with what I've done in the past to return a pdf; you could do the same with your image.

          – Jonathan
          Mar 7 at 19:26













          ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

          – positive perspective
          Mar 7 at 19:28





          ok. thanks a lot, I'm reading about paths to the images in asp.net now to get through this stuff.

          – positive perspective
          Mar 7 at 19:28



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55051196%2fcant-convert-sql-varbinary-to-byte-correctly-and-convert-to-image-in-asp-net%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

          2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

          Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme