Programmatically resize images uploaded

When uploading images to D8 programmatically the setting for Maximum image resolution will be ignored and images will not be scaled down. Some of the images i have to upload are even larger then 10MB.

I am currently using this code.

$  file_type = explode('.', $  image)[1]; $  data = file_get_contents($  image); $  path = 'public://images/';  if (file_prepare_directory($  path, FILE_CREATE_DIRECTORY)) {    $  file = file_save_data($  data, $  path . md5($  image) . '.' . $  file_type, FILE_EXISTS_REPLACE);    $  node = Node::create(array(     'type' => 'image',     'title' => $  image,     'field_image' => array(       'target_id' => $  file->id(),     ),   ));   $  node->save();  } 

I’ve tried to work with ImageStyle::load('max_2600x2600'), but that will only create a style in styles directory.

It would be possible to use a custom shell command but i would love to use the Drupal 8 way. How to make sure original images will get resized?

Android camera intent for 3 images destroys and recreates fragment and crashes onActivityResult [on hold]

There are 3 imageviews on which I want to set image captured from camera. Camera intent is fired from a fragment, picture is being captured, but when returned to app fragment gets destroyed and is recreated.

I am saving all 3 image paths in list but since fragment is destroyed list is reinitialized and size of list becomes 0.

The intent fired for camera is:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);             if (getActivity() != null) { if(takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {                     // Create the File where the photo should go                     File photoFile = null;                     try {                         photoFile = createImageFile();                     } catch (IOException ex) {                         // Error occurred while creating the File                     }                     // Continue only if the File was successfully created                     if (photoFile != null) {                         photoPaths.add(photoFile.getAbsolutePath()); Uri photoURI=FileProvider.getUriForFile(getContext(),"com.example.parking.fileprovider",photoFile);                         takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI); startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);                     }                 }             } 

And in onActivityResult the image intent is fetched:

Bitmap bitmap; // here imgCount is for checking number of images captured since I only want to capture 3 images. if (imgCount == 0) { bitmap = cropImageForApp(preview1, photoPaths.get(imgCount)); preview1.setImageBitmap(bitmap); imgCount++;                 } else if (imgCount == 1) { bitmap = cropImageForApp(preview2, photoPaths.get(imgCount));                     preview2.setImageBitmap(bitmap);                     imgCount++;                 } else if(imgCount ==2) { bitmap =cropImageForApp(preview3,photoPaths.get(imgCount)); preview3.setImageBitmap(bitmap); imgCount++; } ````````````````````````````````````````````````````` Expected Result:The image to be captured and set on imageview.  And the error I am getting is: `````````````````````````````````````````````````````````` java.lang.RuntimeException: Unable to resume activity {com.parking.vehicleparking/com.parking.vehicleparking.activity.RegisterActivity}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {com.parking.vehicleparking/com.parking.vehicleparking.activity.RegisterActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3657) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3697) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2927) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$  H.handleMessage(ActivityThread.java:1639) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:6662) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$  MethodAndArgsCaller.run(RuntimeInit.java:547) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) Caused by: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {com.parking.vehicleparking/com.parking.vehicleparking.activity.RegisterActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at android.app.ActivityThread.deliverResults(ActivityThread.java:4365) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3629) at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3697)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2927)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$  H.handleMessage(ActivityThread.java:1639)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:176)  at android.app.ActivityThread.main(ActivityThread.java:6662)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$  MethodAndArgsCaller.run(RuntimeInit.java:547)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)  Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java:437) at com.parking.vehicleparking.fragment.CaptureImageFragment.onActivityResult(CaptureImageFragment.java:143) at android.support.v4.app.FragmentActivity.onActivityResult(FragmentActivity.java:160) at com.parking.vehicleparking.activity.RegisterActivity.onActivityResult(RegisterActivity.java:275) at android.app.Activity.dispatchActivityResult(Activity.java:7341) at android.app.ActivityThread.deliverResults(ActivityThread.java:4361) at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3629)  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3697)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2927)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$  H.handleMessage(ActivityThread.java:1639)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:176)  at android.app.ActivityThread.main(ActivityThread.java:6662)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$  MethodAndArgsCaller.run(RuntimeInit.java:547)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)  `````````````````````````````````````````````````````````````` 

How do I add hyperlinks and images to the template(A1), to use the below could and use mail merge to send out my mails?

function getRowsData(sheet, range, columnHeadersRowIndex) {   columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;   var numColumns = range.getEndColumn() - range.getColumn() + 1;   var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);   var headers = headersRange.getValues()[0];   return getObjects(range.getValues(), normalizeHeaders(headers)); }   function getObjects(data, keys) {   var objects = [];   for (var i = 0; i < data.length; ++i) {     var object = {};     var hasData = false;     for (var j = 0; j < data[i].length; ++j) {       var cellData = data[i][j];       if (isCellEmpty(cellData)) {         continue;       }       object[keys[j]] = cellData;       hasData = true;     }     if (hasData) {       objects.push(object);     }   }   return objects; }   function normalizeHeaders(headers) {   var keys = [];   for (var i = 0; i < headers.length; ++i) {     var key = normalizeHeader(headers[i]);     if (key.length > 0) {       keys.push(key);     }   }   return keys; }  function normalizeHeader(header) {   var key = '';   var upperCase = false;   for (var i = 0; i < header.length; ++i) {     var letter = header[i];     if (letter == ' ' && key.length > 0) {       upperCase = true;       continue;     }     if (!isAlnum(letter)) {       continue;     }     if (key.length == 0 && isDigit(letter)) {       continue; // first character must be a letter     }     if (upperCase) {       upperCase = false;       key += letter.toUpperCase();     } else {       key += letter.toLowerCase();     }   }   return key; }   function isCellEmpty(cellData) {   return typeof(cellData) == 'string' && cellData == ''; }   function isAlnum(char) {   return char >= 'A' && char <= 'Z' ||     char >= 'a' && char <= 'z' ||     isDigit(char); }   function isDigit(char) {   return char >= '0' && char <= '9'; }   function sendEmails() {   var ss = SpreadsheetApp.getActiveSpreadsheet();   var dataSheet = ss.getSheets()[0];   var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 4);    var templateSheet = ss.getSheets()[1];   var emailTemplate = templateSheet.getRange("A1").getValue();   var emailTemplate2 = templateSheet.getRange("A2").getValue();     var objects = getRowsData(dataSheet, dataRange);    // For every row object, create a personalized email from a template and send   // it to the appropriate person.   for (var i = 0; i < objects.length; ++i) {     // Get a row object     var rowData = objects[i];     var file = DriveApp.getFilesByName('2019_MA_BenefitsGuide.pdf')     var file1 = DriveApp.getFilesByName('List of Acceptable Documents.pdf')      var emailText = fillInTemplateFromObject(emailTemplate, rowData);     var emailText2 = fillInTemplateFromObject(emailTemplate2, rowData);     var emailSubject = 'Mail Merge Test';      MailApp.sendEmail(rowData.emailAddress,                       emailSubject,                        emailText,                        {attachments: [file.next(), file1.next()]} );    } }  function fillInTemplateFromObject(template, data) {   var email = template;   // Search for all the variables to be replaced, for instance $  {"Column name"}   var templateVars = template.match(/$  \{\"[^\"]+\"\}/g);    // Replace variables from the template with the actual values from the data object.    for (var i = 0; i < templateVars.length; ++i) {      var variableData = data[normalizeHeader(templateVars[i])];     email = email.replace(templateVars[i], variableData || '');   }    return email; } 

How do I add hyperlinks and images to the template(A1), to use the below could and use mail merge to send out my emails?

Pulling images from Windows 10 Lock Screen to a different folder

Windows 10 has an interesting feature where it will display “fun facts” and images on the lock screen. Occasionally, these images are something I would want to use for a background.

These images are stored in %LocalAppData%\Packages\Microsoft.Windows.ContentDeliveryManager_cw5n1h2txyewy\LocalState\Assets.

As I wasn’t certain if _cw5n1h2txyewy would be constant on the Microsoft.Windows.ContentDeliveryManager folder, I wanted to just search the %LocalAppData%\Packages directory for Microsoft.Windows.ContentDeliveryManager*, and pull the first directory that matches that pattern.

Then, in that directory, I wanted to copy the images and read a “magic number” from each image, which can vary but determines the image type. In this case, I use the first 4 bytes as 0x89 0x50 0x4E 0x47 (or 0x89 then PNG), or bytes 6 through 9 as 0x4A 0x46 0x49 0x46 (JFIF) or 0x45 0x78 0x69 0x66 (Exif). The first condition would add the png extension, the second would add jpg.

The first function is my detect_file_type, which evaluates the file contents and determines what image type it is:

fn detect_file_type(data : &Vec<u8>) -> Option<String> {     if data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47 { // ?PNG         Some("png".to_string())     } else if data[6] == 0x4A && data[7] == 0x46 && data[8] == 0x49 && data[9] == 0x46 { // JFIF         Some("jpg".to_string())     } else if data[6] == 0x45 && data[7] == 0x78 && data[8] == 0x69 && data[9] == 0x66 { // Exif         Some("jpg".to_string())     } else {          None     } } 

This is rather simple.

Next, I wanted my directory search function:

fn find_dir(search : &str, path : PathBuf) -> Option<PathBuf> {     for entry in fs::read_dir(path).unwrap() {         let path = entry.unwrap().path();         if path.is_dir() {             if path.file_name().unwrap().to_str().unwrap().starts_with(search) {                 return Some(path);             }         }     }     return None; } 

Again, rather simple. We stuck to Option with both of these so that we can handle the error cases (if we need to).

And finally, we have all the critical work:

fn main() {     let args =          App::new("Pull Windows Lock-Screen Pictures")             .version("0.1")             .about("Loads the images used for the main Windows 10 Lock-Screen backgrounds to the specified folder (or './out' if not specified).")             .arg(Arg::with_name("destination")                 .help("The destination directory ('./out' by default)")                 .takes_value(true)                 .required(false))             .get_matches();      let my_dirs = Directories::with_prefix("windows_lock_screen_pictures", "Windows_Lock_Screen_Pictures").unwrap();     let home = my_dirs.bin_home().parent().unwrap().parent().unwrap().join("Packages");     let dir = find_dir("Microsoft.Windows.ContentDeliveryManager", home).unwrap().join("LocalState").join("Assets");      for entry in fs::read_dir(dir).unwrap() {         let path = entry.unwrap().path();         if !path.is_dir() {             let data = fs::read(&path).unwrap();             let path_str = path.display().to_string();             let file = path.file_name().unwrap().to_str().unwrap().to_string();              let path_ext =                 match detect_file_type(&data) {                     Some(path_ext) => {                         let mut res = ".".to_string();                         res.push_str(&path_ext);                         res                     },                     _ => "".to_string()                 };              let mut base_dest_dir = "".to_string();             let mut default = std::env::current_dir().unwrap().to_str().unwrap().to_string();             default.push_str("\out\");             let dest_dir = args.value_of("destination").unwrap_or(&default);             base_dest_dir.push_str(dest_dir);              if !Path::new(&base_dest_dir).exists() {                 fs::create_dir(Path::new(&base_dest_dir)).expect("Could not create directory");             }              base_dest_dir.push_str(&file);             base_dest_dir.push_str(&path_ext);              println!("{} -> {}", path_str, base_dest_dir);             fs::write(Path::new(&base_dest_dir), data).expect("Could not write file");         }     } } 

Overall, we kept things rather small, but still allowed flexibility (and most of the safety we needed).

Our whole program is as follows:

extern crate clap; extern crate dirs;

use std::fs::{self}; use std::path::{Path,PathBuf}; use clap::{App,Arg}; use dirs::{Directories};  fn detect_file_type(data : &Vec<u8>) -> Option<String> {     if data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4E && data[3] == 0x47 { // ?PNG         Some("png".to_string())     } else if data[6] == 0x4A && data[7] == 0x46 && data[8] == 0x49 && data[9] == 0x46 { // JFIF         Some("jpg".to_string())     } else if data[6] == 0x45 && data[7] == 0x78 && data[8] == 0x69 && data[9] == 0x66 { // Exif         Some("jpg".to_string())     } else {          None     } }  fn find_dir(search : &str, path : PathBuf) -> Option<PathBuf> {     for entry in fs::read_dir(path).unwrap() {         let path = entry.unwrap().path();         if path.is_dir() {             if path.file_name().unwrap().to_str().unwrap().starts_with(search) {                 return Some(path);             }         }     }     return None; }  fn main() {     let args =          App::new("Pull Windows Lock-Screen Pictures")             .version("0.1")             .about("Loads the images used for the main Windows 10 Lock-Screen backgrounds to the specified folder (or './out' if not specified).")             .arg(Arg::with_name("destination")                 .help("The destination directory ('./out' by default)")                 .takes_value(true)                 .required(false))             .get_matches();      let my_dirs = Directories::with_prefix("windows_lock_screen_pictures", "Windows_Lock_Screen_Pictures").unwrap();     let home = my_dirs.bin_home().parent().unwrap().parent().unwrap().join("Packages");     let dir = find_dir("Microsoft.Windows.ContentDeliveryManager", home).unwrap().join("LocalState").join("Assets");      for entry in fs::read_dir(dir).unwrap() {         let path = entry.unwrap().path();         if !path.is_dir() {             let data = fs::read(&path).unwrap();             let path_str = path.display().to_string();             let file = path.file_name().unwrap().to_str().unwrap().to_string();              let path_ext =                 match detect_file_type(&data) {                     Some(path_ext) => {                         let mut res = ".".to_string();                         res.push_str(&path_ext);                         res                     },                     _ => "".to_string()                 };              let mut base_dest_dir = "".to_string();             let mut default = std::env::current_dir().unwrap().to_str().unwrap().to_string();             default.push_str("\out\");             let dest_dir = args.value_of("destination").unwrap_or(&default);             base_dest_dir.push_str(dest_dir);              if !Path::new(&base_dest_dir).exists() {                 fs::create_dir(Path::new(&base_dest_dir)).expect("Could not create directory");             }              base_dest_dir.push_str(&file);             base_dest_dir.push_str(&path_ext);              println!("{} -> {}", path_str, base_dest_dir);             fs::write(Path::new(&base_dest_dir), data).expect("Could not write file");         }     } } 

Where does OrFox save images?

OrFox 1.0beta1 has a function to save images. Yet, there’s no information where the image is stored inside and outside the application nor a configuration option to pre-determine the storage location. Maybe someone can share this well-hidden information.

Saved pictures don’t appear in a gallery application which searches in default pathes which makes it possible that they’re not saved at all and no error message is shown to the user.

Do Google Photos’ images take up quota when appearing in Google Drive’s Google Photos folder?

In the following scenario:

  1. Google Photos is set to “high quality”, i.e. not included in quota
  2. Google Drive always seems to take quota for media
  3. Google Drive is set to show Google Photos

Will images that were uploaded directly to Google Photos’ website count as part of Google Drive’s quota?

Review on ImageSEO – SEO Tool for Images based on AI and ML

Hey guys,

My name is Matthieu, I have just (co)founded https://imageseo.io and I'm looking for feedbacks from people dealing with SEO and Marketing.

[​IMG]

In a nutshell, our tool shows you what's missing in your image SEO strategy and provide you with suggestions to optimize your filenames and alt tags using Machine Learning and AI. We have developed it because images are the best way to trigger a call for…

Review on ImageSEO – SEO Tool for Images based on AI and ML