Commit c987d682 authored by Niklas de Vries's avatar Niklas de Vries

Merge branch 'feature/create-from-string' into 'master'

added createFromString method

See merge request !9
parents 29d31806 efd8f9bf
......@@ -118,8 +118,43 @@ class MediaService
$media = $this->getNewMediaObject();
$media->setFilehash($imageData['md5'])
->setFilename($imageData['path'])
->setMediatype($imageData['type']);
->setFilename($imageData['path'])
->setMediatype($imageData['type']);
$this->getEm()->persist($media);
}
return $media;
}
/**
* @param string $base64String
* @param bool $searchForExisting
*
* @return Media
* @throws MediaException
*/
public function createFromString($base64String, $searchForExisting = false)
{
try {
$media = $this->findByMd5(md5($base64String));
if ($media !== null && $searchForExisting) {
return $media;
}
if (!$searchForExisting) {
throw new MediaException('MD5 already in DB - use searchForExisting');
}
} catch (EntityNotFoundException $e) {
$imageData = $this->storeBase64Image($base64String);
$media = $this->getNewMediaObject();
$media->setFilehash($imageData['md5'])
->setFilename($imageData['path'])
->setMediatype($imageData['type']);
$this->getEm()->persist($media);
}
......@@ -359,6 +394,54 @@ class MediaService
return (isset($map[$mime])) ? $map[$mime] : '.unknown';
}
/**
* @param string $base64String
* @param string $format
*
* @return array
*
* @throws MediaException
* @throws \Exception
*/
public function storeBase64Image($base64String, $format = 'jpeg')
{
if (empty($base64String)) {
throw new MediaException('File not found');
}
$data = explode(',', $base64String);
if (sizeof($data) != 2) {
throw new MediaException('Corrupted data');
}
$decoded = base64_decode($data[1]);
$md5 = md5($decoded);
$path = $this->createDirectoryByFilename($md5);
$target = $path.'/'.$md5.'.'.$format;
Image::fromData($decoded)
->setForceCache(false)
->cropResize($this->getConfig('converter')['size']['max_width'], $this->getConfig('converter')['size']['max_height'])
->save($target, $format, $this->getConfig('converter')['quality']);
list($width, $height, $type, $attr) = getimagesize($target);
$result = array(
'path' => $this->getRelativePath($target),
'md5' => $md5,
'width' => $width,
'height' => $height,
'type' => image_type_to_mime_type($type),
);
#dump($result);
// don't do this
// @unlink($input);
return $result;
}
/**
* @param string $input
* @param string $format
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment