Load image from project

Asked

Viewed 576 times

2

I have a project developed from a console application in Visual C#, in which sends emails, the text being in html format.

Today I put an image inside that html the following way:

"<img src='" + "http://www.site.com.br/logotipo.png" + "' width='300' height='70'></img>"

I would like to change that, taking away this link, leaving the image in the project, and from there upload the image. how could I be doing this ?

  • The ideal is that the image is available at some address or online Cdn, otherwise it will as an attachment in the email, which will increase the volume of data in sending and receiving.

1 answer

1


You can convert it to a string on base 64 and put it into src of the image:

I’ll consider that you have a System.Drawing.Image.

First, convert to a byte array (byte[]):

    /// <summary>
    /// Converte um objeto System.Drawing.Image em um array de bytes
    /// </summary>
    /// <param name="foto">System.Drawing.Image</param>
    /// <returns>byte[]</returns>
    public static byte[] ConvertImageToByte(System.Drawing.Image foto, System.Drawing.Imaging.ImageFormat format )
    {
        if (foto != null)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                foto.Save(stream, format);
                //stream.Flush();
                byte[] pic = stream.ToArray();
                return pic;
            }
        }
        else return null;
    }

-Using the function:

 System.Drawing.Image imagem = .... Origem da sua imagem;

 byte[] bImage = ConvertImageToByte(imagem,System.Drawing.Imaging.ImageFormat.Png);

Then convert the byte[] for string:

 string base64String = Convert.ToBase64String(bImage , 0, bImage.Length);

Then put it in html:

string html = "<img class=""plan-cover"" src=""data:image/png;base64," + base64String + """>";

Note. If you need to set the image size (smaller than the original), it compensates to resize the object Image and not in the html. The amount of data sent will only be necessary.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.