Home > Mobile >  How to Convert Apps Script 'application/octet-stream' PNG to JPG without Writing to Drive
How to Convert Apps Script 'application/octet-stream' PNG to JPG without Writing to Drive

Time:02-16

Using Apps Script, I want to fetch a PNG from a remote source, convert that PNG to JPG, and then write the JPG as a new file to Google Drive.

The problem, I believe, is that the remote source is serving the image as 'application/octet-stream' via the content-type header.

The following code works by first writing the PNG file to Google Drive, and then converting that file to JPG. It writes two files to the 'My Drive' root in Google Drive.

  function test1() {
    var response = UrlFetchApp.fetch("https://www.jotform.com/widget-uploads/imagepreview/220373803783154/edd2d7dfile_example_PNG_500kB620b9cedd9f5e.png");
    var blob = response.getBlob();
    var png = DriveApp.createFile(blob);
    var jpg = DriveApp.createFile(png.getAs('image/jpeg'));
  }

However, I would prefer to convert the PNG to JPG without first writing the file to Google Drive. That is, it would be preferred to create/convert the file in memory without the additional step of writing the file to Google Drive. But the following does not work:

  function test2() {
    var response = UrlFetchApp.fetch("https://www.jotform.com/widget-uploads/imagepreview/220373803783154/edd2d7dfile_example_PNG_500kB620b9cedd9f5e.png");
    var blob = response.getBlob();
    var png = DriveApp.createFile(blob);
    var jpg = DriveApp.createFile(blob.getAs('image/jpeg'));
  }

and results in the following error:

Exception: Converting from application/octet-stream to image/jpeg is not supported.

I have tried various combinations of Utilities.newBlob with methods of class Blob() such as getDataAsString(), getBytes(), etc. in order to accomplish converting PNG to JPG without first writing a file to Google Drive. But I must admit I do not understand the various methods/outputs and all result in the error above.

Is it possible to accomplish this and, if so, how? Or, is it just the nature of the 'application/octet-stream' content-type to have to first download/write the file before anything can be done with it?

CodePudding user response:

In your situation, how about the following modification?

Modified script:

function test2() {
  var response = UrlFetchApp.fetch("https://www.jotform.com/widget-uploads/imagepreview/220373803783154/edd2d7dfile_example_PNG_500kB620b9cedd9f5e.png");
  var blob = response.getBlob().setContentTypeFromExtension(); // <--- Modified
  var png = DriveApp.createFile(blob);
  var jpg = DriveApp.createFile(blob.getAs('image/jpeg'));
}
  • By this modification, 2 files of PNG and JPEG are created.
  • I think that var blob = response.getBlob().setContentTypeFromExtension(); can be also modified to var blob = response.getBlob().setContentType(MimeType.PNG);.

References:

  • Related