in drupal 7 you can work with ckeditor and imce modules.
after you've installed these two modules:
in imce config, under "Configuration profiles" you can add new profile and edit it's setting and under "Directories" add directories that you want the user access and add images.
go back to imce config page and under "Role-profile assignments" attach a role ...
When using the field module, I found this was better:
$this_field_image = field_view_field('node',$node,'field_image');
using field_view_field() provides additional advantages whereby one can set an array of display settings:
$hide_labels = array('label'=...
If you use entity query you can filter the entities by type before uploading them.
$ids = \Drupal::entityQuery('media')
$medias = Media::loadMultiple($ids);
For Drupal 8 it would go like following. First add the file and get a file ID. Then create the node and attach the given file ID.
$data = file_get_contents(__DIR__ . '/images/my_image.jpeg');
$file = file_save_data($data, 'public://my_image.jpeg');
$node = \Drupal\node\Entity\Node::create([
'type' => 'page',