C# Generate Canvas Image with Bitmap like Javascript does - javascript

I'm trying to make an image like I'm doing it in javascript with BITMAP but I'm having some issues. First the font looks thicker than javascript and positioning it doesn't work well
The Javascript looks like:
var el = document.createElement("canvas");
el.width = 32, el.height = 32;
var cnt = el.getContext("2d");
cnt.font = "12pt Arial";
cnt.fillText("Hey", 2, 24);
el.toDataURL();//Data image so u can see the javascript image
The C# I made looks like:
Bitmap objBmpImage = new Bitmap(32, 32);
Font objFont = new Font("Arial", 12, FontStyle.Regular, GraphicsUnit.Point);
Graphics objGraphics = Graphics.FromImage(objBmpImage);
objGraphics.Clear(Color.Transparent);
Brush textBrush = new SolidBrush(Color.Black);
objGraphics.DrawString("Hey", objFont, textBrush, 1, 12);//This doesnt position it right I think
objBmpImage.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);//This image is thicker font
So problems I got is
1) Text doesn't position in right place
2) Image font looks Thicker than javascript one
3) Want also to have same data:image url as the javascript in c#

Related

Import "img.svg" into Canvas already used by WebGL

I am drawing a 2D Simulation into a Canvas using WebGL and JavaScript
let gl = c3d.getContext('webgl', {preserveDrawingBuffer: true});
I want to add my company-logo "logo.svg" in the corner of my simulation. I wanted to ask what the best possible solution for my porblem is. I am wondering if i need to write another shader and do all the rendering on every simulation step. Or if there is a simple way to import the svg into the Canvas. I need both the simulation and logo to be in the same canvas because i am downloading the end Result as PNG/JPG.
This is not a WebGL solution but you could modify your download code to use a second canvas to attach the logo:
var c3d = document.getElementById('c3d');
var c2d = document.getElementById('c2d');
var gl = c3d.getContext('webgl');
var c2 = c2d.getContext('2d');
gl.clearColor(1,0,0,1);
gl.clear(gl.COLOR_BUFFER_BIT);
// Base64 encode WebGL output
var glImage = new Image();
glImage.src = c3d.toDataURL('image/png');
// Base64 encode company logo
var logoImage = new Image();
logoImage.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='50' height='50'%3E%3Crect width='50' height='50' style='fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)' /%3E%3C/svg%3E";
// Combine both images on a canvas
c2.drawImage(glImage, 0, 0);
c2.drawImage(logoImage, 0, 0);
// Here you will download the image as before, but I'm just
// appending it as an img to show that the result is correct
var finalImage = new Image();
finalImage.src = c2d.toDataURL('image/png');
document.body.append(finalImage);
<canvas id="c3d"></canvas>
<canvas id="c2d"></canvas>

Remove object's background & resize object to its content in fabric js

Not sure if I put the right title in the question.
In my project user drops a clothing item to the canvas. Usually the clothing item has some white background and looks like this:
I apply RemoveColor filter and remove white background. But still the object has the same size as it had before. What I wan to is clip image like this:
Removing the unnecessary background.
How can I do this and is it possible at all?
The general pipeline is as follows:
Load the image and convert to gray scale
Threshold image and get a binary image
Apply morphological operation, in your case closing should do it. Invert the image to get black background and white foreground.
Find connected regions and select largest as you region of interest
Crop it out.
EDIT
Here is some sample code in Python (using opencv and skimage libraries).
img = cv2.imread('test2.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
t, bw_img = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
closing = cv2.morphologyEx(bw_img, cv2.MORPH_CLOSE, np.ones((3, 3)))
closing = cv2.bitwise_not(closing)
labels, num = measure.label(closing, background=0, connectivity=2, return_num=True)
max_size, max_blob = 0, None
for l in range(1, num+1):
blob = np.zeros_like(labels)
blob[labels == l] = 1
nz = np.count_nonzero(blob)
if nz > max_size:
max_size = nz
max_blob = blob
assert(max_blob is not None)
x, y = np.nonzero(max_blob)
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)
max_blob = max_blob[xmin: xmax, ymin:ymax]
# Resized color image
img = img[xmin: xmax, ymin:ymax]
EDIT2 Images corresponding to steps of the code

Javascript SVG clipto with clip rule (fabricjs)

There is the exemple in img
http://imgur.com/rFdcctc
I have a background where i put an image (phone case).
After that i put a rectangle on the top side (50% top). (canvas)
On that i put an svg that is an another mask (that follow the case curves).
The svg is the same as the entire background in size. So to only have the top of the SVG i "clip" a rectangle on to it.
var clipTo = function(ctx) {
var w = mask.width, h = mask.height;
var x = -w/2, y = -h/2;
var rx = 0, ry = 0;
ctx.moveTo(x+rx, y);
ctx.lineTo(x+w-rx, y);
ctx.lineTo(x+w, y+(h/2)-ry);
ctx.lineTo(x+rx,y+(h/2));
ctx.lineTo(x,y+ry);
ctx.closePath();
};
mask.setClipTo(clipTo);
And it works fine. But when i put a dragable image on it the image is mask by the SVG but not the clip rectangle, as if the clip is still there. (in the image, the content of the red rectangle should be invisible)
I have found that there is a clip-rule :
https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-rule
that could maybe with luck enventually should do it, but i have no idea how to apply it in javascript (i use fabricjs)
So if someone has an idea... :)
Thank you

Dynamically generated favicon

Would it be possible using only JavaScript and HTML to dynamically generate a favicon, using the current page's favicon as a background, and a random number in the foreground?
For example, lets say the current favicon looks similar to this:
======================
====XXXXXXXXXXXXXX====
====X=================
====X=================
====X=====XXXXXXXX====
====X============X====
====X============X====
====XXXXXXXXXXXXXX====
======================
If possible, how would I get it to look something similar to this using only JavaScript and HTML:
======================
====XXXXXXXXXXXXXX====
====X=================
====X=================
====X=====XXXXXXXX====
====X=========--111--=
====X=========--1-1--=
====XXXXXXXXXX----1--=
==============--1111-=
map:
= : white background
x : Original Favicon image
- : Red generated image with a number
1 : White text
Ideas:
Canvas?
Data Uri's?
EDIT: Got it working with
var canvas = document.createElement('canvas');
canvas.width = 16;canvas.height = 16;
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = '/favicon.ico';
img.onload = function() {
ctx.drawImage(img, 0, 0);
ctx.fillStyle = "#F00";
ctx.fillRect(10, 7, 6, 8);
ctx.fillStyle = '#FFFFFF';
ctx.font = 'bold 10px sans-serif';
ctx.fillText('2', 10, 14);
var link = document.createElement('link');
link.type = 'image/x-icon';
link.rel = 'shortcut icon';
link.href = canvas.toDataURL("image/x-icon");
document.getElementsByTagName('head')[0].appendChild(link);
}
You can actually run chrome and paste this:
javascript: var canvas = document.createElement('canvas');canvas.width = 16;canvas.height = 16;var ctx = canvas.getContext('2d');var img = new Image();img.src = '/favicon.ico';img.onload = function() {ctx.drawImage(img, 0, 0);ctx.fillStyle = "#F00";ctx.fillRect(10, 7, 6, 8);ctx.fillStyle = '#FFFFFF';ctx.font = 'bold 10px sans-serif';ctx.fillText('2', 10, 14);var link = document.createElement('link');link.type = 'image/x-icon';link.rel = 'shortcut icon';link.href = canvas.toDataURL("image/x-icon");document.getElementsByTagName('head')[0].appendChild(link);}
into the browser and see it in action.
You might take a look at this question, which discusses how to change the favicon dynamically. Also here is a site that claims to play a game in the favicon using only JavaScript, canvas, and the data URI, which should work in all modern browsers except IE. Not sure if that would fulfill your requirements or not, but you can try reverse engineering how it works.
Here's an SO answer that explains how to use the canvas element to read the favicon data and get the image data out, which then can be modified and composed into a new icon.
I don't know about doing it all in the browser, but it would be easy to have a server endpoint that accepted parameters in the URL and returned a composed favicon. Then Javascript could modify the favicon url to get the image it wanted.
favicon.js does exactly this. This library can display a counter in the bottom right corner of the favicon, among other features.

Image png color css or html or javascript

I have this image in my website, is a png.I want to know if there is anyway with HTML5 , javascript or css to change the color of the image? At least the image change to white (invert color black to white, not the transparency).
Thanks in advance
You cannot do this in plain HTML or CSS. You can do this with JS/HTML Canvas, but there is probably a much easier and more compatible solution than JS/HTML Canvas for performing image manipulation.
Depending on what you are trying to do, you may just want to create a second image that you swap out with the first. There are also some decent image manipulation packages in server-side languages like PHP, if you need to do something more dynamic.
If you are set on using js, the code below is modified from your example.
Using your example:
window.onload = function(){
var imageObj = new Image();
imageObj.onload = function(){
drawImage(this);
};
imageObj.src = "darth-vader.jpg";
};
function drawImage(imageObj){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 69; //update these to set the image position
var destY = 50;
context.drawImage(imageObj, destX, destY);
var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
var data = imageData.data;
for (var i = 0, n = data.length; i < n; i += 4) {
if(data[i] == 0 && data[i+1] == 0 && data[i+2] ==0){ //if black, ie. red, green, and blue are all 0
//switch to white
data[i] = 255; //red
data[i+1] = 255; //green
data[i+2] = 255; //blue
}
// i+3 is alpha (the fourth element)
}
// overwrite original image
context.putImageData(imageData, 0, 0);
}
You haven't explained why you aren't just using Photoshop to do it, but I assume you have your reasons.
Well wanted to support all... but for
now Firefox, Chrome will be nice.
Latest versions , would be nice ... I
guess with canvas HTML5 is possible.
I'm not sure how well it works with transparent .pngs, but you could try Pixastic.
Here's a demo of the "Invert" effect: http://www.pixastic.com/lib/docs/actions/invert/
You've lucked out with the browser support for "Invert" - it works in even IE:
Although a few of the effects in
Pixastic are simulated in IE with
proprietary filters, most actions and
effects will not work without a canvas
enabled browser. Please consider using
either Firefox, Opera or Safari

Categories

Resources