'Google Apps Script to get the current selected image mime type

I have a Google Doc file where I need to determine the MIME type of the file

I didnt find any methods that can get the mime type of the selected (SELECT USING SINGLE ON THE IMAGE USING MOUSE) image.

enter image description here

I have tried with

  var doc = DocumentApp.getActiveDocument();
  var docText = doc.editAsText();
  var content = docText.getSelection();

But it will not get the image type. Any help is greatly appreciated.



Solution 1:[1]

You can use the method for Document getSelection() instead of using editAsText().

Then from the selection you will get a range, from that range you get the elements it has. In this case since it is only one image it should have only one element, but you can use a for loop to treat all the elements of the range.

This is a simplified version without the for loop:

  var doc = DocumentApp.getActiveDocument()
  var selection = doc.getSelection()
  var range = selection.getRangeElements();
  Logger.log(range[0].getElement().getType())

UPDATE

Based on @Cooper comment you can use his method shared with the one on this answer as:

function myFunction() {
  var doc = DocumentApp.getActiveDocument()
  var selection = doc.getSelection()
  var range = selection.getRangeElements();
  var image = range[0].getElement();
  Logger.log(image.getBlob().getContentType())
}

This will return image/jpeg

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1