Adobe photoshop - convert image to bitmap using a script - javascript

I'm trying to write a script in Photoshop using JavaScript. The goal for this script is to automatically convert from RGB to Bitmap mode. I don't want use the manual way: image->mode->greyscale->image->mode->bitmap.
After reading the “JavaScript Scripting Reference” I understand that I need to do it the same as the manual way but using code.
I convert the RGB image to grayscale using the changeMode method. This works:
app.activeDocument.changeMode(ChangeMode.GRAYSCALE)
But, when I try to change from greyscale to bitmap I just can't. The document does not explain clearly how it works. I did try to follow the document but I don't have a lot of experience in JavaScript. Here is my current attempt:
```js
// Save the current preferences
var startRulerUnits = app.preferences.rulerUnits
var startTypeUnits = app.preferences.typeUnits
var startDisplayDialogs = app.displayDialogs
// Set Adobe Photoshop to use pixels and display no dialogs
app.preferences.rulerUnits = Units.PIXELS
app.preferences.typeUnits = TypeUnits.PIXELS
app.displayDialogs = DialogModes.NO
app.activeDocument.changeMode(ChangeMode.GRAYSCALE)
app.activeDocument.changeMode(ChangeMode.Bitmap)
// app.activeDocument.close()
Could you please provide a simple example about how to do it?

Related

How to easily import OpenCV.js into a .js file?

I implemented a CNN that I use on a web application via Tensorflow.js.
I need to preprocess my webcam photos to be accepted by my CNN model. So I want to use OpenCV.js in my .js file but I can't figure out how to simply import this library into my .js file where I turn my canvasElement into a tensor using the tf.browser.fromPixels() function of Tensorflow.js.
The tutorials I see show the use of OpenCV.js in the .html file directly inside a <script>, whereas I would like to use it in my javascript file.
I would especially like to use the method cv.cvtColor(). If not, do you have another solution to convert my canvasElement to grayscale?
The script tag will import OpenCV into the webpage (be sure to load this before you load your code that needs to use it - order matters in HTML). You should then be able to access the OpenCV class / object to call its functions with your canvas data to do your pre processing, and then write that back out and convert to tensor in TF.js land.
If you want to quickly convert canvas to greyscale there are many ways to do this - eg how you average the colours etc will effect the greyscale image you get out.
Here is one method: http://www.vapidspace.com/coding/2012/02/26/converting-images-to-grayscale-using-the-canvas/
Here is the code from that site in case it gets removed:
function grayscale (input,output) {
//Get the context for the loaded image
var inputContext = input.getContext("2d");
//get the image data;
var imageData = inputContext.getImageData(0, 0, input.width, input.height);
//Get the CanvasPixelArray
var data = imageData.data;
//Get length of all pixels in image each pixel made up of 4 elements for each pixel, one for Red, Green, Blue and Alpha
var arraylength = input.width * input.height * 4;
//Go through each pixel from bottom right to top left and alter to its gray equiv
//Common formula for converting to grayscale.
//gray = 0.3*R + 0.59*G + 0.11*B
for (var i=arraylength-1; i>0;i-=4)
{
//R= i-3, G = i-2 and B = i-1
//Get our gray shade using the formula
var gray = 0.3 * data[i-3] + 0.59 * data[i-2] + 0.11 * data[i-1];
//Set our 3 RGB channels to the computed gray.
data[i-3] = gray;
data[i-2] = gray;
data[i-1] = gray;
}
//get the output context
var outputContext = output.getContext("2d");
//Display the output image
outputContext.putImageData(imageData, 0, 0);
}
Notice here how they use a formula to calc gray. Depending on your needs you may want to use different ratios of the RGB mix to get the grayscale image.
Personally I would strongly recommend using vanilla JS here as it's very easy to do and you dont need to include OpenCV just to do grayscale which is a massive overhead to include that file for such a task. If you are using some of the more advanced features of OpenCV too then maybe that is a reason to then use it.

How can I draw from ImageData to canvas with zoom in Haxe?

Well, I fill ScreenBuffer:ImageData 480x360 and then want to draw it to the canvas 960x720. The task is to decrease the fillrate; the nowadays pixels are very small and we can make them bigger with some quality loss. I look for the operator with 2D-accelaration. But we can't write directly to js.html.Image and ImageData hasn't link to js.html.Image. I found an example for pure JS:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas
However, it doesn't want to work in Haxe because there isn't 'zoom' element. And there is some information about restrictions in HTML at copying from one image to another.
Many thanks for answers!
The compiler writes "js.html.Element has no field getContext"
getElementById()'s return type is the generic js.html.Element class. Since in your case, you know you're dealing with a <canvas>, you can safely cast it to the more specific CanvasElement. This then lets you call its getContext() method:
var canvas:CanvasElement = cast js.Browser.document.getElementById('zoom');
var zoomctx = canvas.getContext('2d');

how to get the html file of an edited canvas in html5

I am trying to make a website which helps its users to create a page by dragging and dropping elements on the canvas. The user should be able to save the html file of the edited canvas. I cannot figure how to convert the changes made to the canvas to an html file.
I don't think it's possible to get Markup out of canvas. I've searched it for a month but can't find a valid solution. but may be some experts may know. Best of luck buddy.
Canvas is basically just a bit-map image. Whatever you draw on the canvas is stored as pixels not as elements. So changes to the canvas are just changes in pixel values. To do what you wish you would need to store your 'elements' as 'objects' within your code where each 'object' stores all the required data for your 'element'.
it would then be possible to open a new window and export code into it using document.writeln
The code below may give you an idea of what sort of thing would be needed
newwindow=window.open('','_blank');
newwindow.document.writeln('<!DOCTYPE HTML>');
newwindow.document.writeln('<html>');
newwindow.document.writeln('<head>');
newwindow.document.writeln('<style>');
newwindow.document.writeln('#element0 {');
newwindow.document.writeln('background:'+ obj0.background+';');
newwindow.document.writeln('width:'+ obj0.width+';');
newwindow.document.writeln ('}');
newwindow.document.writeln('</style>');
newwindow.document.writeln('</head>');
newwindow.document.writeln('<body>');
newwindow.document.writeln('<div id="element0"></div>');
newwindow.document.writeln('</body>');
newwindow.document.writeln('</html>');
newwindow.document.writeln('<html>');
newwindow.document.close();
Hope this helps
Canvas won't help you here for anything other than to visualize the objects you have dropped onto it.
You need to record the objects you drop in a "shadow" structure behind the scene sort of. That is to say: build a object list internally which you then can use as source data to render:
Canvas visualization of it
Raw HTML code from it.
You can for example drop an image to the canvas and your code will record a new object (intention with the following code is to show the principle not to provide a full working solution):
var myObjects = [];
/// a drop occurred
var o = new myElement(x, y, width, height, id, type);
myElement is a pre-defined object that you set up in advance to hold the given arguments.
Then push the object to your object stack and render it to canvas:
myObjects.push(o);
for(var i = 0, o; o = myObjects[i]; i++) {
/// draw the look of this object here to canvas
}
When you then need a HTML version of it you do the same:
for(var i = 0, o; o = myObjects[i]; i++) {
var el = '<' + o.type + ' id="' + o.id + ' .... other things here
}
This way you can produce canvas graphics, HTML, send data over a socket etc.
The key in these sort things is to keep raw base data available. In this case it would be the element type you want to drop, its position and dimension. For HTML you also have to consider things as nesting etc. but that would require a bit more code than shown here.

Javascript + ActionScript: How to convert bytearray returned from Actionscript to image in Javascript

I have bytearray returned from ActionScript to Javascript through ExternalInterface call. Now, i have to convert this byteaarray to image in Javascript code. pls help...with any sample code...
Thanks in advance...
I see two possible solutions to this problem, neither of which I have tested so try them out:
HTML5 Canvas
First, using ActionScript convert your byte array to integer array. You will need four values for:
Red
Green
Blue
Alpha
Transfer this to Javascript, either using string representation or plain numbers and then load these numbers into the canvas:
var canvasData = ; // data from actionscript
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imgData=ctx.createImageData(100,100);
for (var i=0;i<imgData.width*imgData.height*4;i+=4)
{
imgData.data[i+0]=canvasData[i][0]; // red
imgData.data[i+1]=canvasData[i][1]; // green
imgData.data[i+2]=canvasData[i][2]; // blue
imgData.data[i+3]=canvasData[i][3]; // alpha
}
ctx.putImageData(imgData,10,10);
Base64-encoded through CSS
If you don't want to rely on HTML5, use ActionScript to convert the byte array to a base64 string and then insert the image using the following css rule:
background-image: url(data:image/png;base64,__base64_data__);
and replace __base64_data__ with the generated string. This could be done dynamically using JQuery:
$('#img').css("background-image", "url(data:image/png;base64,__base64_data__)");
This also seems to be a much more efficient method than HTML5 Canvas, although actual performance will depend on the image size.
You can store your data in an ArrayBuffer and inject this into a canvas to display as explained here :
https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/

SVG to HTML map and area

I have been trying to convert map in SVG to HTML area map for three days. I`am trying to do that with this SVG.
I've tried to convert this SVG with several methods and programs, but all of them failed.
e.g.: inkscape, inkscapeMap, Adobe Illustrator, Polygonator, SVGtoHTML and more.
So I wrote my own PHP script to do the job. Its works fine, but it converts only polygons. But there are two paths in SVG which need to be convert to polygon as well. I've tried to convert these paths into polygons in Illustrator and Inkscape, but apparently there is no way how to force these programs to convert path into polygons. (SVG editors probably decide alone, if they do the conversion or not). I find this topic on SO. But I'am not able to get the JS work - I dont know what the param sample is, and more - browser said that function createElementNS is unknown.
The best result I'am able to reach is this HTML, but there is still two region missing (because they are in SVG in paths)
I would be pleased for any clue.
QUESTIONS
1) How to transform SVG paths into polygons? Is that possible?
2) Is there any software which converts SVG into HTML area maps?
3) Could you show my example parametrs, in this JS function (function written Phrogz):
function polygonSampledFromPath(path,samples){
var doc = path.ownerDocument;
var poly = doc.createElementNS('http://www.w3.org/2000/svg','polygon');
var points = [];
var len = path.getTotalLength();
var step = step=len/samples;
for (var i=0;i<=len;i+=step){
var p = path.getPointAtLength(i);
points.push( p.x+','+p.y );
}
poly.setAttribute('points',points.join(' '));
return poly;
}
3ad) Why is function createElementNS unknown?
PS: I hope you understand my English :)

Categories

Resources