Set background of a div from a generated image - c#

I am programmatically creating an image via C#, and I'm wondering how can I use this created image as a background of a div.
To explain it better, here's an example:
public string BackImage()
{
System.Drawing.Image img = //generated image goes here
var ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg);
return Convert.ToBase64String(ms.ToArray());
//should I return it in a different way?
}
This gives me the image that I can use, now how would I set this image to be a background of a div?
<div id="main">
</div>
I have tried using background-image:url(data:image/jpeg;base64,#Html.Action("BackImage"))" but the browser starts freezing because of the image.
Is there some simpler way of doing it?
Thanks.

Two ways:
Simple:
Save your image in a temp folder and in your css class or style definition use
background-image: url('whatevertheurlis')
A bit more complex:
Create an IHttpHandler implementation to deliver the generated image. The css/style background-image setting is different only in the Url part.
I've done both before and the choice was based on the requirements of the number of different images to create and lifetime.

Related

Adding Image with url to clipboard

I'm trying to figure out how to get an image added to the clipboard with an associated URI.
Adding a link to text is easy:
string html = #"Version:0.9
StartHTML:<<<<<<<1
EndHTML:<<<<<<<2
StartFragment:<<<<<<<3
EndFragment:<<<<<<<4
SourceURL: <<<<<<<5
<html>
<body>
<!--StartFragment-->
<a href='aria: 73571 73570'>test 73571 73570</a>
<!--EndFragment-->
</body>
</html>";
string link = html;
Clipboard.SetText(link, TextDataFormat.Html);
but its not obvious what to do with a picture such as a bitmap.
Has anyone done this?
--- additional info ---
Just to clarify - the image I need to use is a bitmap generated by the program. I need to associate the image with a URI so that when pasted into something like Word, the user can click on the image to go to the link. Adding the bitmap to the clipboard on its own I can do, but its the URI part with it that I'm not sure of.
---- Another edit -----
I've tried going the embedded encoded image route by creating a string with the following in it:
Version:0.9
StartHTML:000089
EndHTML:9575818
StartFragment:000242
EndFragment:9575780
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML clipboard</title>
</head>
<body>
<!--StartFragment--><a href='aria: 73571 73570'><img src='data:image/png;base64,### Encoded Image removed for brevity ##'>
<!--EndFragment-->
</body>
</html>
if saved as an HTML file, this opens in a browser perfectly and the image lets me click on the link with no problem.
When I tried to use the clipboard:
DataObject obj = new DataObject();
obj.SetData(DataFormats.Html, new MemoryStream(encoding.GetBytes(htmlResult)));
Clipboard.SetDataObject(obj, true);
htmlresult is the string containing the html fragment as shown before. When I try to paste into word, I can't get anything out of it.
I'm now running out of ideas..
You can put multiple items on the clipboard simultaneously. Currently, you're only putting the html content on the clipboard, but not an actual image, and thus, applications pasting it will most likely not see it as image. You'll need to put both into the DataObject before putting it on the clipboard.
One thing I can see is an issue is the fact that the html fragment does not contain a url at all. It contains a raw data block as Base64. If you want it to point to a url, then you should give it a real url, rather than the data:image/png;base64, block. The html block you put on the clipboard is supposed to be additional metadata to go alongside an image, not the image itself.
Also, what is that aria: 73571 73570? That's not a url either.
Anyway, the proper way to put things onto the clipboard from stream is the following:
using (MemoryStream htmlStream = new MemoryStream(encoding.GetBytes(htmlResult)))
{
DataObject obj = new DataObject();
// The html content.
obj.SetData(DataFormats.Html, htmlStream);
// As standard bitmap
obj.SetData(DataFormats.Bitmap, image);
// The 'copy=true' argument means any streams that are used
// can be safely disposed after the operation.
Clipboard.SetDataObject(obj, true);
}
The mentioned image is the image. I'm not sure if this works the same way in wpf though; I've been doing this kind of stuff with the System.Drawing classes.
Do note that this kind of clipboard handling has no transparency support. Technically, the clipboard has no image transparency support, but certain programs can read other formats (like png) from the clipboard to get around that. See this answer for more information on that, though do note that that answer is not written for wpf.

img tag doesnt print thumbnailed photo

im doing a project using .net MVC web Application.
i recently used a code to create a new thumbnail to photos (re defining the sizes of a photo) . and now i'm trying to print the photos using the 'img' tag of HTML but without success.
the thumbnail creating code :
Image thumbnail = Image.FromFile(destPath);
thumbnail = (Image)(new Bitmap(thumbnail, new Size(this.m_thumbnailSize, this.m_thumbnailSize)));
thumbnail.Save(destPathThumb);
now for the img printing :
#Html.DisplayFor(modelitem=>item)
<img class="img-rounded" style="border-radius:50%" src=#item alt="">
item is the path to the picture and it is currect (ive checked serveral times).
any ideas what i could be ?
thank you for helping me ! :)
EDIT: the img tag prints normal pictures -> pictures that my program did not create(as i said,my program created thumbnail pictures)
I wonder if it is not releasing the file lock on the image, I have had that problem in the past. You have to be very careful about releasing those Image and Bitmap objects.
Something like this might work, as it will dispose the image before the page starts using it:
using(Image thumbnailoriginal = Image.FromFile(destPath)){
using(Image thumbnail = (Image)(new Bitmap(thumbnailoriginal, new Size(this.m_thumbnailSize, this.m_thumbnailSize)))){
thumbnail.Save(destPathThumb);
}
}
It seems like a lot of brackets on the end but thats ok.
If it still does not work, can you post the html that is sent to the browser, you can do that using "View page source" from the right-click menu in Chrome.
Now we have the html that is going to the browser, we can see that the src attribute is pulling directly from the C drive, rather than from a web url:
<img class="img-rounded" style="border-radius:50%" alt="" src="C:\Users\Operu\Desktop\dest\Thumbnails\2018\6\Sasuke.png">
Normally we would want to see something more like this:
<img class="img-rounded" style="border-radius:50%" alt="" src="\Thumbnails\Sasuke.png">
Could you post the model and controller files next please, so we can see what type of object the #item is when it hits your view. Then we can hopefully get it to pull the relative url address instead of the file location.

Missing styles on images when sending email with html embedded

I have to embeded an image in an email
<img src="....." style="float:right;height;400px;"/>
I create and alternate view this way
try{
System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html);
AlternateView avHTMLImage = AlternateView.CreateAlternateViewFromString(msgMail.Mensaje, mimeType);
LinkedResource lrHTMLImage;
System.IO.MemoryStream img = new System.IO.MemoryStream(Imagen.Image2Bytes(ie.img));
lrHTMLImage = new LinkedResource(img, System.Net.Mime.MediaTypeNames.Image.Jpeg);
lrHTMLImage.ContentId = ie.nombreImg;
avHTMLImage.LinkedResources.Add(lrHTMLImage);
avHTMLImage.ContentId = ie.nombreImg;
this.mail.AlternateViews.Add(avHTMLImage);
}
But it is attaching and embedding the image without the settings of float neither height I'm telling it
try and avoid using css where possible in an email. you may find that it's something to do with perhaps the loading order of the css? Some basics to adhere to just in case http://kb.mailchimp.com/campaigns/ways-to-build/css-in-html-email. Put the styling in, the old way eg...
<img src="....." align="right" width="..%" />
and then set the width, making sure that the image is proportionally correct to the width. Setting heights in an email is tricky as clients like outlook and online email viewed in IE will ignore and use the default image size.
FYI also use
display:inline-block
on your images to avoide unwanted margins in gmail

Where i can store image for custom control?

Now, i developing a WinForms application. I need to create a custom control. My custom control uses a pictures. I don't want store these pictures in project resources file.
global::Wrigley_Data_Mart_Manager_2.Properties.Resources.previous_16x16;
I want to store pictures in resources file of custom control. But it's very uncomfortable. (designer always delete pictures from there). Where i can store image for my custom control? I want to my custom control was self-sufficient and that it can be used in other projects.
If you don't want to use a Resource (resx) then you could always include the image file within the project as an embedded resource.
You would create a folder to hold the image(s), and invoke "Add Existing", adding the images you'd like to embed into the project. Then in the Properties window for each file, for the "Build Action" selection, highlight the "Embedded Resource" option.
To access that file, you'd call Assembly.GetManifestResourceStream(string) with the full namespace of the project + the folder path within the project:
For Example, with Project Name: "MyCompany.MyTestProject" and you store the image(s) in the "Images" folder as "Images/image1.gif",
The namespace would then be:
Assembly.GetManifestResourceStream("MyCompany.MyTestProject.Images.image1.gif")
An alternative could be converting them to byte arrays and storing them as BLOBs in your database.
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
Then convert them back:
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}

Converting HTML Table into Image File

Is there any way to Convert HTML table to Image file? I have one HTML table which contains controls like Labels, GridView, and CheckBoxes. How can we convert this table into Image file for creating a PDF file?
This is not a trivial task. Ultimately, you need an HTML renderer to convert the HTML to pixels.
Fortunately, you don't need to write your own. You can use the WebBrowser control.
You can see some code I wrote to extract a thumbnail image from a given URL in the article Creating Website Thumbnails in ASP.NET.
If this is a one-off, load it up in your browser and take a screenshot (Alt-PrtScr on windows for just the current application)
If you need to do this repeatedly/in an automated way, you can either automate a browser control or you can use a headless browser
You should also look into WebKit2Png which will render the page in the same manner as Chrome/other webkit browsers and then save that as a png. It can optionally simulate javascript/etc too
Similarly, there's a wkhtmltopdf which works on all platforms
Converting HTML Table into Image File
$("#selfAssessmentPowerPointDownload").on('mouseover', function () {
var element = $("#html-content-holder"); // global variable
var getCanvas; // global variable
html2canvas(element, {
onrendered: function (canvas) {
getCanvas = canvas;
var imgageData = getCanvas.toDataURL("image/png");
var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#selfAssessmentPowerPointDownload").attr("download", "gridData.png").attr("href", newData);
}
});
});
<button id="selfAssessmentPowerPointDownload">Download</button>
<table id="html-content-holder"></table>
Datatables is a powerful jquery plugin for working with tables. One of the option that datatables offered is make a pdf or excel from your table. You can see find many examples in it's website.

Categories