How to get text from an image placed in a cell using Google Apps Script - image

I want to get text from an image placed in a cell using Google Apps Script.
What code do I write in Google Apps Script?enter image description here
Can the cell be saved as an image and the text read?

I believe your goal is as follows.
You have a Google Spreadsheet where the images are put into the cells. In this case, the images are directly put into the cells without URLs and the built-in function. The images show some texts.
You want to retrieve the images and retrieve the texts from the images.
Unfortunately, in the current stage, there are no built-in methods for directly retrieving the images in the cells. So, in this case, I use this workaround for retrieving the images from the cells. And, in order to convert the texts from the image, Drive API is used.
When these are reflected in a sample script, it becomes as follows.
Usage:
1. Install a Google Apps Script library.
In this workaround, DocsServiceApp (Author: me) of a Google Apps Script library is used. Please install this library. You can see how to install it at here.
2. Sample script.
Please copy and paste the following script to the script editor of Spreadsheet. And, please set your sheet name.
function myFunction() {
const sheetName = "Sheet1"; // Please set your sheet name.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const spreadsheetId = ss.getId();
const ar = DocsServiceApp.openBySpreadsheetId(spreadsheetId).getSheetByName(sheetName).getImages();
const res = ar.map(({ range, image }) => {
const tempId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_DOCS, title: "temp" }, image.blob).id;
const text = DocumentApp.openById(tempId).getBody().getText();
Drive.Files.remove(tempId);
return { cell: range.a1Notation, text: text.trim() };
});
console.log(res);
}
In this script, the images in the cells are retrieved using a library, and the images are converted to Google Documents. And, the text is retrieved from Google Documents.
3. Enable Drive API.
Please enable Drive API at Advanced Google services. Ref
4. Testing.
When the above script is run for your provided Spreadsheet, the following result can be seen in the log.
[
{"cell":"A1","text":"098765431 ZYX"},
{"cell":"A2","text":"1234567890 abcdef"},
{"cell":"A3","text":"098765431 ZYX"},
{"cell":"A4","text":"1234567890 abcdef"},
{"cell":"A5","text":"1234567890 abcdef"},
{"cell":"A6","text":"098765431 ZYX"},
{"cell":"A7","text":"098765431 ZYX"}
]
Note:
In this answer, I propose a simple method. When your sample Spreadsheet is used, the processing time was about 30 seconds. If your actual Spreadsheet has a lot of images, it might be required to split the cells and use the script. Please be careful about this.
References:
DocsServiceApp (Author: me)
Files: insert
Files: delete

Related

`filter.applyTo is not a function` error when try to change image src using setSrc() in fabric js

Currently, I am Working on image editor that allows me to crop an image and apply a filter.
I am using fabric js version 1.7.22.
I want to implement crop functionality.
so my cropping flow is like Below :
crop image using a plugin and ger base64 of the cropped image.
generate blobUrl from base64 which help to display image in fabric js canvas.
After Cropping the image, I Just replace old image src with new One.
It works fine when an image has no filter.
but when I try to set a filter in the image first then try to replace src using setSrc() function.
It throws an error like Below
filter.applyTo is not a function
I have created one fiddle for demonstrating to replace src after the apply filter.
https://jsfiddle.net/Mark_1998/98gLhcb4/1/
And I Can't upgrade my fabric js version. If any patch Available then
Please Help Me.
The problem lies in this piece of code:
canvas.getActiveObject().setSrc('http://fabricjs.com/assets/pug_small.jpg', function(){
canvas.renderAll();
}, canvas.getActiveObject().toObject());
You're passing canvas.getActiveObject().toObject() as an options object, which is assigned to your image in setSrc() -> setElement() -> _initConfig().
toObject() serializes your fabric.Image, and filters array no longer contains the actual fabric.Filter, but rather a serialized version of it. So, it does not have a prototype with applyTo() method on it, hence the error filter.applyTo is not a function when fabric tries to reapply filters to your image after setSrc().
Instead of passing the whole serialized object as options, you'll need to pick the properties you actually want to be passed. As I'm not sure about what your requirements are, I tried replacing the above code with the following and it worked for me:
var options = canvas.getActiveObject().toObject();
delete options.filters;
options.crossOrigin = true;
canvas.getActiveObject().setSrc('http://fabricjs.com/assets/pug_small.jpg', function(){
canvas.renderAll();
}, options);
Note the options.crossOrigin = true - you won't be able to apply filters without it.

Show images inside a pdf created with Gloogle Apps Script Blob

I am creating PDF files using blobs in Google Apps Script from a HTML code, but the problem is that HTML code has an image (referenced by "http") but the created pdf can't show it.
This is my code
function createBlobPDF(myMessage,myTitle){
var blobHTML = Utilities.newBlob(myMessage, "text/html", myTitle+ ".html");
var myPDF = blobHTML.getAs("application/pdf");
return myPDF;
}
Any solution? thanks!!
If the images in HTML are loaded from URLs, the converted PDF file doesn't include the images. If you want to include the images in the converted PDF file, please put the images to HTML as base64 data.
In order to confirm this situation, please see the following sample script. This sample script puts an image as URL and base64 data. The result is displayed them to a dialog and created a PDF file.
When you use this script, please copy and paste to the script editor of Spreadsheet.
Sample script :
function myFunction() {
// image
var url = "https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a";
var blob = UrlFetchApp.fetch(url).getBlob();
var b64 = blob.getContentType() + ';base64,'+ Utilities.base64Encode(blob.getBytes());
var html = "URL<img src=\"" + url + "\">Base64<img src=\"data:" + b64 + "\">";
var h = HtmlService.createHtmlOutput(html);
// Open dialog with the images.
SpreadsheetApp.getUi().showModalDialog(h.setWidth(500).setHeight(200), 'Sample');
// Create from HTML to PDF file.
DriveApp.createFile(h.getAs("application/pdf").setName("text.pdf"));
}
Result of dialog :
Both images can be seen.
Result of PDF file :
Only the image of base64 can be seen.
Note :
This is a simple script. So please modify this to your environment.
References :
How to display Base64 images in HTML?
If I misunderstand your question, I'm sorry.
I tested converting html to pdf with image content. It works but in the bottom of a box, the color does not work! How to make the color to appear in the background of a box?
I wanted to show you my little treatment as an example "<>" but it doesn't work because there is no window for code.gs . Shame...
In short, see the final result in pdf, attached
before clicking on the "validate" button, the screen is displayed, see the screenshot below. this is where you "capture" the HTML presentation and then run to convert HTML to PDF.
after clicking on "validate", here is the result, see below :
normally, I would like to have the same result between screen and PDF.
Then, how to do it ?

How to replace text by using Google scripts?

I want to show an image from Google Drive in a Google Spreadsheet.
I have to replace the text:
open?
for:
uc?export=download&
in the Shareable link:
https://drive.google.com/open?id=0BwJUnx7uETDmaG42eGdEVUVocU0
I have tried this solution https://stackoverflow.com/a/42819032/2661411:
"
I made a two lines script to use the share link of an image in Google Drive.
Go to Tools > Script editor.
Copy, paste the following code
Click on run for permission
function DRIVE_IMAGE(link){
prefix_url = "https://docs.google.com/uc?export=download&";
link.replace("open?", "uc?export=download&");
}
Using the script :
Copy the share link of your image in Google Drive.
Go to a cell
Enter the formula =IMAGE(DRIVE_IMAGE("COPIED_LINK")) "
But didn't work for me, it said:
TypeError: Cannot call method "replace" of undefined. (line 3, file "ImgView")
Any ideas? I would like it to keep it simple.
You need to use https://docs.google.com/uc?export=download&id=<<IMAGE ID>>. Refer the below formula.
=image("https://docs.google.com/uc?export=download&id=0BwJUnx7uETDmaG42eGdEVUVocU0")
Script
/**
* #customfunction
*/
function DRIVE_IMAGE(link){
var newLink = link.replace("https://drive.google.com/open?", "https://docs.google.com/uc?export=download&");
return newLink;
}
Now, you can use the formula =IMAGE(DRIVE_IMAGE("https://drive.google.com/open?id=0BwJUnx7uETDmaG42eGdEVUVocU0"))

using coldfusion 8 to add images to rows in an excel document

Using Coldfusion 8 has anyone been able to either embed images into a excel spreadsheet (xlsx) or link them via img src?
Some background info: The cf server will pickup an excel document with product rows. Based on the product id and style etc, I be able to find or create an image that gets added as the first column into the existing excel doc.
I know coldfusion 9 has a function called SpreadsheetAddImage, unfortunately I'm on cf 8 with no chance to upgrade.
I am not sure what you are currently using to manipulate the xlsx files. However, the spreadsheet functionality in CF9 utilizes POI, which can obviously be used from CF8 as well. It just requires a little more low level code.
Pre-requisites:
Though POI is bundled with CF8, it is an old version. You need a newer version to manipulate .xlsx files. You can either use the javaLoader -OR- replace the existing jars in {cf_root}\lib folder. Note, I do not know if replacing the jars has any negative side effects.
Adding Images:
Excel does not really support <img> tags, only hyperlinks. However, you can embed images within the workbook like SpreadsheetAddImage does. As outlined in the POI's Busy Developers Guide, the basic process is:
Load the xlsx file with the WorkBookFactory
Grab the binary of each image and add it to the workbook
Anchor each image to the desired cells
Save the modified workbook to back to disk
Example:
<cfscript>
// ..
// load the xlsx file with the javaLoader
factory = loader.create("org.apache.poi.ss.usermodel.WorkbookFactory");
input = loader.create("java.io.FileInputStream").init( "c:/path/to/someFile.xlsx" );
workbook = factory.create( input );
input.close();
// get the desired sheet and load helper objects (once)
sheet = workbook.getSheet("Your Sheet Name");
patriarch = sheet.createDrawingPatriarch();
helper = workbook.getCreationHelper();
// add the image to the workbook
imageBytes = fileReadBinary( "c:/path/to/someImage.jpg" );
imageIndex = workbook.addPicture( imageBytes, workbook.PICTURE_TYPE_JPEG );
// anchor the picture to the first cell ie A1
anchor = helper.createClientAnchor();
anchor.setRow1( javacast("int", 0) ); // row of first cell (zero based)
anchor.setCol1( javacast("int", 0) ); // column of first cell (zero based)
picture = patriarch.createPicture( anchor, imageIndex );
picture.resize(); // only supported for jpg and png
// save it back to disk
outstream = loader.create("java.io.FileOutputStream").init( "c:/path/to/outFile.xlsx"" );
workbook.write( outstream );
outstream.flush();
outstream.close();
</cfscript>
New Columns
Ironically, inserting a new column is trickier than adding an image. Last I checked, POI still lacked a built in function for inserting new columns. So you would need to shift all existing cells to the right before inserting the images into the first column. The tricky part is maintaining cell formats, merged cells, etcetera.

How to use System.Drawing.Image in RDLC Image Control?

Is it possible to use System.Drawing.Image in an RDLC Image Control?
All I have been reading were 3 methods:
database
embeded resource
external file
Thank you thank you.
EDIT:
Following up from this .NET or C# library for CGM (Computer Graphics Metafile) format? I now got the image in System.Drawing.Image format and want to display it as part of the report (as an image) --- that's what I want to do.
Not sure if this is what you are looking for, but if you have an image in code and you want to show it in the report, create a wrapper object that has a property that returns the image as a byte array and give then an instance of this wrapper-class with the valid image to the report as a ReportDataSource.
Something like:
ReportDataSource logoDataSource = new ReportDataSource();
logoDataSource.Name = "LogoDS";
logoDataSource.Value = new List<LogoWrapper>() { yourLogoWrapper };
localReport.DataSources.Add(logoDS);
In the report you then you can the image as it were from the database
=First(Fields!LogoByteArrayProperty.Value, "LogoDS")
The wrapper looks something like:
class LogoWrapper{
...
public byte[] LogoByteArrayProperty{
get{
// Return here the image data
}
}
}
I use this quite often. It has the advantage that I don't have to add the image to the db or add it as a resource of every report. And furthermore, the app can say which image should be used.
Please note, the given image format must be known from the rdlc-engine.
The last question would be, how to convert a system.drawing.image to a byte array. I work with WPF and therefore, I dont known. But I'm sure google will respond to this question very reliable.
You Can use the 'Database' Source Option along with Parameters to Dynamically set Image Source from Byte Arrays.
Code Behind:
var param2 = new ReportParameter()
{
Name = "CompanyLogo",
Values = { Convert.ToBase64String(*ByteArrayImageObject*) }
};
ReportViewer1.LocalReport.SetParameters(param2);
rdlc File:
1- Add Text Parameters 'CompanyLogo' and 'MIMEType'
2- Set the Value Property of the Image to =System.Convert.FromBase64String(Parameters!CompanyLogo.Value)
3- Set MIME Type Property to
=Parameters!MIMEType.Value
4- Use 'Database' As Source
How can I render a PNG image (as a memory stream) onto a .NET ReportViewer report surface
i am not quite sure what do you want to do with this but in general it is not possible.Image Control is just a image holder in the RDLC files.These 3 options specify the location from where the image control takes the image which to display from- database, embeded resource or external file. If you give me more info on what do you want to achieve i can give you some kind of solution.
Best Regards,
Iordan

Resources