Border-radius gone crazy after crop image from bigger picture by IMAGICK - imagick

I used Imagick to handle all the operations.
$finalWHRatio = $finalW/$finalH;
$im = new \imagick($srcFilePath);
$im -> setResolution(300, 300);
$im -> setImageFormat('gif');
$this->autoRotateImage($im);
$geo = $im->getImageGeometry();
$srcImgWidth = $geo['width'];
$srcImgHeight = $geo['height'];
$srcWHRatio = $srcImgWidth/$srcImgHeight;
$resizedH = '';
$redizedW = '';
if($srcWHRatio > $finalWHRatio){
$resizedH = $finalH;
$resizedW = $srcWHRatio*$finalH;
$im -> resizeImage($resizedW, $resizedH, \Imagick::FILTER_LANCZOS, 1);
$x_crop = $resizedW/2 - ($finalW/2);
$y_crop = 0;
$im -> cropImage($finalW, $finalH, $x_crop, $y_crop);
}else{
$resizedW = $finalH;
$resizedH = $finalW/$srcWHRatio;
$im -> resizeImage($resizedW, $resizedH, \Imagick::FILTER_LANCZOS, 1);
$x_crop = 0;
$y_crop = $resizedH/2 - ($finalH/2);
$im -> cropImage($finalW, $finalH, $x_crop, $y_crop);
}
Now after cropping and resizing I have - 120x120 px image. But when presented on profile page, if cropped from Portrait appears like this
If image is landscape the image border distortion is horizontal.
Is there some other informations encoded into image that should i change? Or its a problem with css?

I used $im -> setImagePage($finalW, $finalH, 0, 0); And now it's working fine

Related

Flutter - Save BlendMode to Image

I'm trying to implement an UI where the user can edit and apply effects to an uploaded image, and want to save the BlendMode merged to the image. It's possible to save the result of the blended image or apply it using the Canvas?
There are some packages that apply some specific filters, but I want something more customizable for the end user.
I already saw some examples of how to implement Canvas to draw images, but can't figure it out how to use to load an image an apply the blend related in the docs. Anyone could give an example?
UPDATED:
For who has the same question, bellow follows the code with how to save a image from canvas to a file with blendMode applied.
But I still haven't the result expected. The quality of the image generated isn't the same as the original image, neither the blend seems to be the blend that i've applied. And i can't save as jpg, just as png file.
So, how can i load an image, apply a blend with canvas and save as a jpg file, without losing quality?
CODE:
const kCanvasSize = 200.0;
class CanvasImageToFile {
CanvasImageToFile._();
static final instance = CanvasImageToFile._();
ByteData _readFromFile(File file) {
// File file = getSomeCorrectFile();
Uint8List bytes = file.readAsBytesSync();
return ByteData.view(bytes.buffer);
}
Future<File> _writeToFile(ByteData data) async {
String dir = (await getTemporaryDirectory()).path;
String filePath = '$dir/tempImage.jpg';
final buffer = data.buffer;
return new File(filePath).writeAsBytes(
buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
}
Future<ui.Image> _loadImageSource(File imageSource) async {
// ByteData data = await rootBundle.load(asset);
ByteData data = _readFromFile(imageSource);
ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
ui.FrameInfo fi = await codec.getNextFrame();
return fi.image;
}
Future<File> generateImage(File imageSource) async {
File imageResult;
ui.Image image;
await _loadImageSource(imageSource).then((value) {
image = value;
});
if (image != null) {
final recorder = ui.PictureRecorder();
var rect =
Rect.fromPoints(Offset(0.0, 0.0), Offset(kCanvasSize, kCanvasSize));
final canvas = Canvas(recorder, rect);
Size outputSize = rect.size;
Paint paint = new Paint();
//OVERLAY - BlendMode uses the previously drawn content as a mask
paint.blendMode = BlendMode.colorBurn;
paint.color = Colors.red;
// paint.colorFilter = ColorFilter.mode(Colors.blue, BlendMode.colorDodge);
// paint = Paint()..color = Colors.red;
// paint = Paint()..blendMode = BlendMode.multiply;
//Image
Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
final FittedSizes fittedSizes =
applyBoxFit(BoxFit.cover, inputSize, outputSize);
final Size sourceSize = fittedSizes.source;
final Rect sourceRect =
Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);
canvas.saveLayer(rect, paint);
canvas.drawImageRect(
image, sourceRect, rect, paint);
canvas.restore();
final picture = recorder.endRecording();
final img = await picture.toImage(200, 200);
final byteData = await img.toByteData(format: ImageByteFormat.png);
await _writeToFile(byteData).then((value) {
imageResult = value;
});
return imageResult;
}
After some research e some adjust at decoding image from png to rawUnmodified in my previous code using (Bitmap package), i could save the image with the original format (jpg) and achieved what i wanted. If there's anyone who have the same question, bellow follows the code to load an image with canvas, apply a blend and write to a file with the same quality:
Future<File> generateImage(
File imageSource, Color color, BlendMode blendMode) async {
File imageResult;
ui.Image image;
await _loadImageSource(imageSource).then((value) {
image = value;
});
if (image != null) {
final recorder = ui.PictureRecorder();
var rect = Rect.fromPoints(Offset(0.0, 0.0),
Offset(image.width.toDouble(), image.height.toDouble()));
final canvas = Canvas(recorder, rect);
Size outputSize = rect.size;
Paint paint = new Paint();
//OVERLAY - BlendMode uses the previously drawn content as a mask
// paint.blendMode = blendMode;
// paint.color = color;
paint.colorFilter = ColorFilter.mode(color, blendMode);
//Image
Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
final FittedSizes fittedSizes =
applyBoxFit(BoxFit.contain, inputSize, outputSize);
final Size sourceSize = fittedSizes.source;
final Rect sourceRect =
Alignment.center.inscribe(sourceSize, Offset.zero & inputSize);
canvas.drawImageRect(image, sourceRect, rect, paint);
final picture = recorder.endRecording();
final img = await picture.toImage(image.width, image.height);
ByteData byteData =
await img.toByteData(format: ui.ImageByteFormat.rawUnmodified);
Bitmap bitmap = Bitmap.fromHeadless(
image.width, image.height, byteData.buffer.asUint8List());
Uint8List headedIntList = bitmap.buildHeaded();
await _writeToFile(headedIntList.buffer.asByteData()).then((value) {
imageResult = value;
});
return imageResult;
}
}

Urhosharp Material.FromImage not woking with some jpg files

I'm using Xamarin.Forms with Urhosharp in my project. I'm tring to set a matrial from an image on a sphere, everything is OK in my Android project but in iOS project, when I set material from some jpg files it doesn't work and all I get is a black screen.
Here is the jpg that works correctly:
And here is the other one that doesn't:
This is my code:
var scene = new Scene();
scene.CreateComponent<Octree>();
// Node (Rotation and Position)
var node = scene.CreateChild("room");
node.Position = new Vector3(0, 0, 0);
//node.Rotation = new Quaternion(10, 60, 10);
node.SetScale(1f);
// Model
var modelObject = node.CreateComponent<StaticModel>();
modelObject.Model = ResourceCache.GetModel("CustomModels/SmoothSphere.mdl");
var zoneNode = scene.CreateChild("Zone");
var zone = zoneNode.CreateComponent<Zone>();
zone.SetBoundingBox(new BoundingBox(-300.0f, 300.0f));
zone.AmbientColor = new Color(1f, 1f, 1f);
//get image from byte[]
//var url = "http://www.wsj.com/public/resources/media/0524yosemite_1300R.jpg";
//var wc = new WebClient() { Encoding = Encoding.UTF8 };
//var mb = new MemoryBuffer(wc.DownloadData(new Uri(url)));
var mb = new MemoryBuffer(PanoramaBuffer.PanoramaByteArray);
var image = new Image(Context) { Name = "MyImage" };
image.Load(mb);
//or from resource
//var image = ResourceCache.GetImage("Textures/grave.jpg");
var isFliped = image.FlipHorizontal();
if (!isFliped)
{
throw new Exception("Unsuccessful flip");
}
var m = Material.FromImage("1.jpg");
m.SetTechnique(0, CoreAssets.Techniques.DiffNormal, 0, 0);
m.CullMode = CullMode.Cw;
//m.SetUVTransform(Vector2.Zero, 0, 0);
modelObject.SetMaterial(m);
// Camera
var cameraNode = scene.CreateChild("camera");
_camera = cameraNode.CreateComponent<Camera>();
_camera.Fov = 75.8f;
_initialZoom = _camera.Zoom;
// Viewport
Renderer.SetViewport(0, new Viewport(scene, _camera, null));
I already tried to change compression level, ICCC profile and ...
I asked the same question in forums.xamarin.com and someone answered the question and I'll share it here :
In iOS every texture needs to have a power of two resolution, like 256 x 256 or 1024 x 512. Check if that is the issue. Additionally check that your using the latest UrhoSharp version.
Also make sure that the image is set as BundleResource in the iOS project.

Unable to port Lumia imaging SDK2.0 to SDK 3.0(UWP)

I am having a tough time converting lumia imaging SDK 2.0 code to SDK3.0 in below specific case. I used to increase/decrease the image quality of JPG file using below code in Windows phone 8.1 RT apps:
using (StreamImageSource source = new StreamImageSource(fileStream.AsStreamForRead()))
{
IFilterEffect effect = new FilterEffect(source);
using (JpegRenderer renderer = new JpegRenderer(effect))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0; // higher value means better quality
compressedImageBytes = await renderer.RenderAsync();
}
}
Now since FilterEffect class has been replaced in SDK 3.0 with EffectList(), I changed code to
using (BufferProviderImageSource source = new BufferProviderImageSource(fileStream.AsBufferProvider()))
{
using (JpegRenderer renderer = new JpegRenderer())
{
IImageProvider2 source1 = new EffectList() { Source = source };
renderer.Source = source1;
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
try
{
var img = await renderer.RenderAsync();
}
catch (Exception ex)
{
;
}
}
}
I am getting InvalidCastException exception. I have tried several combinations but no luck.
I don't really know what is going on with the InvalidCastException, we can continue that discussion in the comments as it will most likely need some back-and-forth.
That said, you could continue without the effect list, and chain effects in the normal way. So to rewrite your scenario:
using (var soruce = new StreamImageSource(...))
using (var renderer = new JpegRenderer(source))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
var img = await renderer.RenderAsync();
}
If you wanted to add an effect (for example a CarttonEffect), just do:
using (var soruce = new StreamImageSource(...))
using (var caroonEffect = new CartoonEffect(source))
using (var renderer = new JpegRenderer(caroonEffect))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
var img = await renderer.RenderAsync();
}
and so on. If you had effects A, B, C and D just make a chain Source -> A -> B -> C -> D -> JpegRenderer.
I am on VS 2015 community version. While digging around this, I got below code working which works exactly same as SDK 2.0. All I did was specified the Size of JpegRenderer. It works for all landscape images but fails to transform the portrait images to correct orientation. There is no exception but result of portrait image is widely stretched landscape image.
I initialized the Size for portrait images to Size(765, 1024) but no impact.
using (JpegRenderer renderer = new JpegRenderer(source))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
try
{
var info = await source.GetInfoAsync();
renderer.Size = new Size(1024, 765);
compressedImageBytes = await renderer.RenderAsync();
}
catch (Exception ex)
{
new MessageDialog("Error while compressing.").ShowAsync();
}
}
I am sorry the working code was using BufferProviderImageSource instead StreamImageSource. Below is the snippet. Few points here:
1) If I don't use Size property I get "The component cannot be found exception".
2) GetInfoAsync(): Yes it was useless for above code but I need to use it to know if image is Landscape or Portrait so that I can initialize Size property of resultant image.
3) If Size property goes beyond 1024x1024 for portrait images I get the exception "Value does not fall within the expected range"
Why lumia made this version so tricky. :(
var stream = FileIO.ReadBufferAsync(file);
using (var source = new BufferProviderImageSource(stream.AsBufferProvider()))
{
EffectList list = new EffectList() { Source = source };
using (JpegRenderer renderer = new JpegRenderer(list))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
renderer.OutputOption = OutputOption.PreserveAspectRatio;
try
{
var info = await source.GetInfoAsync();
double width = 0;
double height = 0;
if (info.ImageSize.Width > info.ImageSize.Height) //landscape
{
width = 1024;
height = 765;
if (info.ImageSize.Width < 1024)
width = info.ImageSize.Width;
if (info.ImageSize.Height < 765)
height = info.ImageSize.Height;
}
else //portrait..
{
width = 765;
height = 1024;
if (info.ImageSize.Width < 765)
width = info.ImageSize.Width;
if (info.ImageSize.Height < 1024)
height = info.ImageSize.Height;
}
renderer.Size = new Size(width, height);
compressedImageBytes = await renderer.RenderAsync();
}
catch (Exception ex)
{
new MessageDialog(ex.Message).ShowAsync();
}
}
}

How to load image in actionscript to stage without changing it's size?

I made an application that the user could load an image, then they could edit it. The problem is, when I load an image for the first time, it loaded with it's original pixel size. But when i load another image, the pixel size differ from the original one.
Here is the function code when image loaded to stage :
function onFileLoadComplete(event:Event):void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onDataLoadComplete);
loader.loadBytes(loadFileRef.data);
loadFileRef = null;
}
function onDataLoadComplete(event:Event):void
{
var bitmapData:BitmapData = Bitmap(event.target.content).bitmapData;
var matrix:Matrix = new Matrix();
matrix.translate(-imageView_mc.x, -imageView_mc.y);
matrix.scale(scaleX, scaleY);
matrix.translate(imageView_mc.x, imageView_mc.y);
imageView_mc.graphics.clear();
imageView_mc.graphics.beginBitmapFill(bitmapData, matrix, false, true);
imageView_mc.graphics.drawRect(0, 0, bitmapData.width, bitmapData.height);
imageView_mc.graphics.endFill();
trace ("Image width: " ,imageView_mc.width, ", Image height: " ,imageView_mc.height);
imageView_mc.width = stage.stageWidth;
imageView_mc.height = stage.stageHeight;
(imageView_mc.scaleX < imageView_mc.scaleY) ? imageView_mc.scaleY = imageView_mc.scaleX : imageView_mc.scaleX = imageView_mc.scaleY;
(imageView_mc.scaleX > imageView_mc.scaleY) ? imageView_mc.scaleY = imageView_mc.scaleX : imageView_mc.scaleX = imageView_mc.scaleY;
imageView_mc.x = 0.5*(stage.stageWidth-imageView_mc.width);
imageView_mc.y = 0.5*(stage.stageHeight-imageView_mc.height);
}
so, is there something wrong with this code? this code is for loading image to stage, then scale it proportionally to stage size.
Any feedback would be really appreciated.
Reset your scale when loaded new image before applying matrix transform.
scaleX = scaleY = 1;

Text on image not appearing, in preview handler vs2005 .net2

hi i am trying to show image of my file in previwew pane i am able to display the image of my file but i am stuck in the part where i need write some text on the image before adding it to preview pane.
// create an image object, using the filename we just retrieved
String strImageFile = file.FullName.Substring(0, file.FullName.Length - 3) + "jpg";
//file.CreationTime.ToString();
//------------------------------------
//Load the Image to be written on.
Bitmap bitMapImage = new System.Drawing.Bitmap(strImageFile);
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
graphicImage.DrawString("AWESOME!", new Font("Arial", 20, FontStyle.Bold), Brushes.Black, new Point(100, 250));
//Save the new image to the response output stream.
bitMapImage.Save(strImageFile, ImageFormat.Png);
//------------------------------------
// Create a picture box control
PictureBox p = new PictureBox();
p.Dock = DockStyle.Fill;
p.Image = bitMapImage;
//p.Image = System.Drawing.Image.FromFile(strImageFile);
p.SizeMode = PictureBoxSizeMode.Zoom;
Controls.Add(p);
//graphicImage.Dispose();
//bitMapImage.Dispose();
Only the image appease and not the text, any idea what i might be missing.
thanks
Narrow it down too:
PictureBox p = new PictureBox();
// create an image object, using the filename we just retrieved
String strImageFile = file.FullName.Substring(0, file.FullName.Length - 3) + "jpg";
Bitmap bitMapImage = new System.Drawing.Bitmap(strImageFile);
Graphics graphicImage = Graphics.FromImage(bitMapImage);
graphicImage.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
graphicImage.DrawString("AWESOME!", new Font("Arial", 20, FontStyle.Bold), Brushes.Black, new Point(100, 250));
graphicImage.DrawImage(bitMapImage, new Rectangle(205, 0, 200, 200), 0, 0, bitMapImage.Width, bitMapImage.Height, GraphicsUnit.Pixel);
p.Image = bitMapImage;
p.Dock = DockStyle.Fill;
Controls.Add(p);
But i am getting an exception on

Resources