JavaME Resize Image - image

I have a byte[] that stores my image.
Now I want to be able to scale it and store it in another byte[].
I know how to scale Bitmaps, and can convert my from byte[] to Bitmap.
But I cant get the scaled Bitmap back into a byte[].
Blackberries
EncodedImage thumbnail = image.scaleImageToFill(50, 50); does nothing.
Im trying to create a thumbnail of 50x50. doesnt have to be exact. That is stored in a byte[].
How do I resize an image stored in a byte[], and keep it in a new byte[].
byte[] imageTaken;
//Create thumbnail from image taken
EncodedImage image = EncodedImage.createEncodedImage(imageTaken, 0, -1);
image.getBitmap();
EncodedImage thumbnail = image.scaleImageToFill(50, 50);
byte[] thumbArray = thumbnail.getData();

try this code
bitmap = resizeImage(your image, 50,50);
private static EncodedImage resizeImage(EncodedImage image, int width, int height) {
if (image == null) {
return image;
}
//return if image does not need a resizing
if (image.getWidth() <= width && image.getHeight() <= height) {
return image;
}
double scaleHeight, scaleWidth;
if (image.getWidth() > width && image.getHeight() > height) { //actual image is bigger than scale size
if (image.getWidth() > image.getHeight()) { //actual image width is more that height then scale with width
scaleWidth = width;
scaleHeight = (double)width / image.getWidth() * image.getHeight();
} else { //scale with height
scaleHeight = height;
scaleWidth = (double)height / image.getHeight() * image.getWidth();
}
} else if (width < image.getWidth()) { //scale with scale width or height
scaleWidth = width;
scaleHeight = (double)width / image.getWidth() * image.getHeight();
} else {
scaleHeight = height;
scaleWidth = (double)height / image.getHeight() * image.getWidth();
}
int w = Fixed32.div(Fixed32.toFP(image.getWidth()), Fixed32.toFP((int)scaleWidth));
int h = Fixed32.div(Fixed32.toFP(image.getHeight()), Fixed32.toFP((int)scaleHeight));
return image.scaleImage32(w, h);
}
Then convert the bitmap to Bytes -
JPEGEncodedImage encoder=JPEGEncodedImage.encode(bitmap,100);
byte[] array=encoder.getData();
int length=array.length;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(length);
Base64OutputStream base64OutputStream = new Base64OutputStream( byteArrayOutputStream );
try{
base64OutputStream.write( array, 0, length );
base64OutputStream.flush();
base64OutputStream.close();
}
catch (IOException ioe){
//Dialog.alert("Error in encodeBase64() : "+ioe.toString());
System.out.println("Error in encodeBase64() : "+ioe.toString());
}
try {
byte[] data = Base64InputStream.decode(byteArrayOutputStream.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

How can I resize and compress an image file in Xamarin [duplicate]

I am working on xamarin.forms. I have to select images from gallery and then resize them and then upload them on server. But I don't know how I can resize selected image in a given particular size?
Please update me how I can do this?
This can be used with a stream (if you're using the Media Plugin https://github.com/jamesmontemagno/MediaPlugin) or standard byte arrays.
// If you already have the byte[]
byte[] resizedImage = await CrossImageResizer.Current.ResizeImageWithAspectRatioAsync(originalImageBytes, 500, 1000);
// If you have a stream, such as:
// var file = await CrossMedia.Current.PickPhotoAsync(options);
// var originalImageStream = file.GetStream();
byte[] resizedImage = await CrossImageResizer.Current.ResizeImageWithAspectRatioAsync(originalImageStream, 500, 1000);
I tried use CrossImageResizer.Current... but I did not find it in the Media Plugin. Instead I found an option called MaxWidthHeight, that worked only if you also add PhotoSize = PhotoSize.MaxWidthHeight option.
For Example :
var file = await CrossMedia.Current.PickPhotoAsync(new PickMediaOptions() { PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 600 });
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions { PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 600 });
Sadly enough there isn't a good cross-platform image resizer (that I've found at the time of this post). Image processing wasn't really designed to take place in a cross-platform environment for iOS and Android. It's much faster and cleaner to perform this on each platform using platform-specific code. You can do this using dependency injection and the DependencyService (or any other service or IOC).
AdamP gives a great response on how to do this Platform Specific Image Resizing
Here is the code taken from the link above.
iOS
public class MediaService : IMediaService
{
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
UIImage originalImage = ImageFromByteArray(imageData);
var originalHeight = originalImage.Size.Height;
var originalWidth = originalImage.Size.Width;
nfloat newHeight = 0;
nfloat newWidth = 0;
if (originalHeight > originalWidth)
{
newHeight = height;
nfloat ratio = originalHeight / height;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
nfloat ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
width = (float)newWidth;
height = (float)newHeight;
UIGraphics.BeginImageContext(new SizeF(width, height));
originalImage.Draw(new RectangleF(0, 0, width, height));
var resizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
var bytesImagen = resizedImage.AsJPEG().ToArray();
resizedImage.Dispose();
return bytesImagen;
}
}
Android
public class MediaService : IMediaService
{
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
// Load the bitmap
BitmapFactory.Options options = new BitmapFactory.Options();// Create object of bitmapfactory's option method for further option use
options.InPurgeable = true; // inPurgeable is used to free up memory while required
Bitmap originalImage = BitmapFactory.DecodeByteArray(imageData, 0, imageData.Length, options);
float newHeight = 0;
float newWidth = 0;
var originalHeight = originalImage.Height;
var originalWidth = originalImage.Width;
if (originalHeight > originalWidth)
{
newHeight = height;
float ratio = originalHeight / height;
newWidth = originalWidth / ratio;
}
else
{
newWidth = width;
float ratio = originalWidth / width;
newHeight = originalHeight / ratio;
}
Bitmap resizedImage = Bitmap.CreateScaledBitmap(originalImage, (int)newWidth, (int)newHeight, true);
originalImage.Recycle();
using (MemoryStream ms = new MemoryStream())
{
resizedImage.Compress(Bitmap.CompressFormat.Png, 100, ms);
resizedImage.Recycle();
return ms.ToArray();
}
}
WinPhone
public class MediaService : IMediaService
{
private MediaImplementation mi = new MediaImplementation();
public byte[] ResizeImage(byte[] imageData, float width, float height)
{
byte[] resizedData;
using (MemoryStream streamIn = new MemoryStream(imageData))
{
WriteableBitmap bitmap = PictureDecoder.DecodeJpeg(streamIn, (int)width, (int)height);
float Height = 0;
float Width = 0;
float originalHeight = bitmap.PixelHeight;
float originalWidth = bitmap.PixelWidth;
if (originalHeight > originalWidth)
{
Height = height;
float ratio = originalHeight / height;
Width = originalWidth / ratio;
}
else
{
Width = width;
float ratio = originalWidth / width;
Height = originalHeight / ratio;
}
using (MemoryStream streamOut = new MemoryStream())
{
bitmap.SaveJpeg(streamOut, (int)Width, (int)Height, 0, 100);
resizedData = streamOut.ToArray();
}
}
return resizedData;
}
}
EDIT: If you are already using FFImageLoading in your project then you can just use that for your platform.
https://github.com/luberda-molinet/FFImageLoading
I fixed in my project, this was the best way for me .
when take photo or get image from gallery you can change size with properties
var file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
PhotoSize = PhotoSize.Custom,
CustomPhotoSize = 90 //Resize to 90% of original
});
for more information: https://github.com/jamesmontemagno/MediaPlugin

Xamarin iOS: How to change the color of a UIImage pixel by pixel

Sorry if this has already been answered somewhere but I could not find it.
Basically, I am receiving a QR code where the code itself is black and the background is white (this is a UIImage). I would like to change to the color of the white background to transparent or a custom color and change the QRCode color from black to white. (In Xamarin iOS)
I already know how to get the color of a specific Pixel using the following code:
static UIColor GetPixelColor(CGBitmapContext context, byte[] rawData,
UIImage barcode, CGPoint pt)
{
var handle = GCHandle.Alloc(rawData);
UIColor resultColor = null;
using (context)
{
context.DrawImage(new CGRect(-pt.X, pt.Y - barcode.Size.Height,
barcode.Size.Width, barcode.Size.Height), barcode.CGImage);
float red = (rawData[0]) / 255.0f;
float green = (rawData[1]) / 255.0f;
float blue = (rawData[2]) / 255.0f;
float alpha = (rawData[3]) / 255.0f;
resultColor = UIColor.FromRGBA(red, green, blue, alpha);
}
return resultColor;
}
This is currently my function:
static UIImage GetRealQRCode(UIImage barcode)
{
int width = (int)barcode.Size.Width;
int height = (int)barcode.Size.Height;
var bytesPerPixel = 4;
var bytesPerRow = bytesPerPixel * width;
var bitsPerComponent = 8;
var colorSpace = CGColorSpace.CreateDeviceRGB();
var rawData = new byte[bytesPerRow * height];
CGBitmapContext context = new CGBitmapContext(rawData, width,
height, bitsPerComponent, bytesPerRow, colorSpace,
CGImageAlphaInfo.PremultipliedLast);
for (int i = 0; i < rawData.Length; i++)
{
for (int j = 0; j < bytesPerRow; j++)
{
CGPoint pt = new CGPoint(i, j);
UIColor currentColor = GetPixelColor(context, rawData,
barcode, pt);
}
}
}
Anyone know how to do this ?
Thanks in advance !
Assuming your UIImage is backed by a CGImage (and not a CIImage):
var cgImage = ImageView1.Image.CGImage; // Your UIImage with a CGImage backing image
var bytesPerPixel = 4;
var bitsPerComponent = 8;
var bytesPerUInt32 = sizeof(UInt32) / sizeof(byte);
var width = cgImage.Width;
var height = cgImage.Height;
var bytesPerRow = bytesPerPixel * cgImage.Width;
var numOfBytes = cgImage.Height * cgImage.Width * bytesPerUInt32;
IntPtr pixelPtr = IntPtr.Zero;
try
{
pixelPtr = Marshal.AllocHGlobal((int)numOfBytes);
using (var colorSpace = CGColorSpace.CreateDeviceRGB())
{
CGImage newCGImage;
using (var context = new CGBitmapContext(pixelPtr, width, height, bitsPerComponent, bytesPerRow, colorSpace, CGImageAlphaInfo.PremultipliedLast))
{
context.DrawImage(new CGRect(0, 0, width, height), cgImage);
unsafe
{
var currentPixel = (byte*)pixelPtr.ToPointer();
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// RGBA8888 pixel format
if (*currentPixel == byte.MinValue)
{
*currentPixel = byte.MaxValue;
*(currentPixel + 1) = byte.MaxValue;
*(currentPixel + 2) = byte.MaxValue;
}
else
{
*currentPixel = byte.MinValue;
*(currentPixel + 1) = byte.MinValue;
*(currentPixel + 2) = byte.MinValue;
*(currentPixel + 3) = byte.MinValue;
}
currentPixel += 4;
}
}
}
newCGImage = context.ToImage();
}
var uiimage = new UIImage(newCGImage);
imageView2.Image = uiimage; // Do something with your new UIImage
}
}
finally
{
if (pixelPtr != IntPtr.Zero)
Marshal.FreeHGlobal(pixelPtr);
}
If you do not actually need access to the individual pixels but the end result only, using CoreImage pre-exisitng filters you can first invert the colors and then use the black pixels as an alpha mask. Otherwise see my other answer using Marshal.AllocHGlobal and pointers.
using (var coreImage = new CIImage(ImageView1.Image))
using (var invertFilter = CIFilter.FromName("CIColorInvert"))
{
invertFilter.Image = coreImage;
using (var alphaMaskFiter = CIFilter.FromName("CIMaskToAlpha"))
{
alphaMaskFiter.Image = invertFilter.OutputImage;
var newCoreImage = alphaMaskFiter.OutputImage;
var uiimage = new UIImage(newCoreImage);
imageView2.Image = uiimage; // Do something with your new UIImage
}
}
The plus side is this is blazing fast ;-) and the results are the same:
If you need even faster processing assuming you are batch converting a number of these images, you can write a custom CIKernel that incorporates these two filters into one kernel and thus only process the image once.
Xamarin.IOS with this method you can convert all color white to transparent for me only works with files ".jpg" with .png doesn't work but you can convert the files to jpg and call this method.
public static UIImage ProcessImage (UIImage image)
{
CGImage rawImageRef = image.CGImage;
nfloat[] colorMasking = new nfloat[6] { 222, 255, 222, 255, 222, 255 };
CGImage imageRef = rawImageRef.WithMaskingColors(colorMasking);
UIImage imageB = UIImage.FromImage(imageRef);
return imageB;
}
Regards

iPhone image orientation wrong when resizing with SkiaSharp

I'm using the SKBitmap.Resize() method in SkiaSharp on a Xamarin.Forms project to resize images for display. The problem I'm encountering is when taking a photo on iOS, when a photo is taken in portrait, the image is displayed with the right side up. Taking a photo on Android, importing from the photo gallery on both an Android and iOS device maintains orientation, but taking a photo in iOS does not. If I don't resize the image using SkiaSharp (just display the image without any resizing), then the image displays with the proper orientation. However that is not a solution as the images need to be resized. Below is my code -
private byte[] GetResizedImageData(string imageName)
{
float resizeFactor = 0.5f;
var filePath = PathUtil.GetImagePath(imageName);
var ogBitmap = SKBitmap.Decode(filePath);
float fWidth = ogBitmap.Width * resizeFactor;
int width = (int) Math.Round(fWidth);
float fHeight = ogBitmap.Height * resizeFactor;
int height = (int) Math.Round(fHeight);
if (height >= 4096 || width >= 4096)
{
width = width * (int)resizeFactor;
height = height * (int)resizeFactor;
}
var scaledBitmap = ogBitmap.Resize(new SKImageInfo( width, height), SKBitmapResizeMethod.Box);
var image = SKImage.FromBitmap(scaledBitmap);
var data = image.Encode(SKEncodedImageFormat.Jpeg, 100);
return data.ToArray();
}
PathUtil.GetImagePath() is just a helper to get platform-specific paths for where the photos are being stored.
For those with the same issue I did the following and would gladly accept input on improvements.
public static SKBitmap HandleOrientation(SKBitmap bitmap, SKCodecOrigin orientation)
{
SKBitmap rotated;
switch (orientation)
{
case SKCodecOrigin.BottomRight:
using (var surface = new SKCanvas(bitmap))
{
surface.RotateDegrees(180, bitmap.Width / 2, bitmap.Height / 2);
surface.DrawBitmap(bitmap.Copy(), 0, 0);
}
return bitmap;
case SKCodecOrigin.RightTop:
rotated = new SKBitmap(bitmap.Height, bitmap.Width);
using (var surface = new SKCanvas(rotated))
{
surface.Translate(rotated.Width, 0);
surface.RotateDegrees(90);
surface.DrawBitmap(bitmap, 0, 0);
}
return rotated;
case SKCodecOrigin.LeftBottom:
rotated = new SKBitmap(bitmap.Height, bitmap.Width);
using (var surface = new SKCanvas(rotated))
{
surface.Translate(0, rotated.Height);
surface.RotateDegrees(270);
surface.DrawBitmap(bitmap, 0, 0);
}
return rotated;
default:
return bitmap;
}
And then use the following to get the original orientation.
// TODO: Improve this.. I do not know how to "reset"
// the inputStream, so new it up twice. :/
using (var inputStream = new SKManagedStream(imageIn))
{
using (var codec = SKCodec.Create(inputStream))
{
orientation = codec.Origin;
}
}
.......
Then
SKBitmap orientedWExif = HandleOrientation(resized, orientation);
SkiaSharp didn't actually provide a method for me to manipulate and change the orientation of the image. In the end I ended up altering the orientation as I captured and saved the image using platform specific code.
Thank you #ttugates Your answer helped me to fix issue with the orientation rotation. Just want to update your answer as there is some deprecated code.
using (var inputStream = new SKManagedStream(await file.ReadAllStreamAsync()))
{
using (var codec = SKCodec.Create(inputStream))
{
orientation = codec.EncodedOrigin;
}
}
public static SKBitmap HandleOrientation(SKBitmap bitmap, SKEncodedOrigin orientation)
{
SKBitmap rotated;
switch (orientation)
{
case SKEncodedOrigin.BottomRight:
using (var surface = new SKCanvas(bitmap))
{
surface.RotateDegrees(180, bitmap.Width / 2, bitmap.Height / 2);
surface.DrawBitmap(bitmap.Copy(), 0, 0);
}
return bitmap;
case SKEncodedOrigin.RightTop:
rotated = new SKBitmap(bitmap.Height, bitmap.Width);
using (var surface = new SKCanvas(rotated))
{
surface.Translate(rotated.Width, 0);
surface.RotateDegrees(90);
surface.DrawBitmap(bitmap, 0, 0);
}
return rotated;
case SKEncodedOrigin.LeftBottom:
rotated = new SKBitmap(bitmap.Height, bitmap.Width);
using (var surface = new SKCanvas(rotated))
{
surface.Translate(0, rotated.Height);
surface.RotateDegrees(270);
surface.DrawBitmap(bitmap, 0, 0);
}
return rotated;
default:
return bitmap;
}
}
Workable solution for resize and handle orientation
public class ImageResizer : IImageResizer
{
private const int Quality = 75;
public byte[] Resize(byte[] data, int newWidth, int newHeight)
{
using (var inputStream = new SKMemoryStream(data))
{
using (var codec = SKCodec.Create(inputStream))
{
using (var original_old = SKBitmap.Decode(codec))
{
int sourceWidth = original_old.Width;
int sourceHeight = original_old.Height;
float nPercentW = ((float) newWidth / (float) sourceWidth);
float nPercentH = ((float) newHeight / (float) sourceHeight);
float nPercent = nPercentH < nPercentW ? nPercentH : nPercentW;
int destWidth = (int) (sourceWidth * nPercent);
int destHeight = (int) (sourceHeight * nPercent);
using (SKBitmap original = original_old.Resize(new SKImageInfo(destWidth, destHeight), SKFilterQuality.Medium))
{
var useWidth = original.Width;
var useHeight = original.Height;
Action<SKCanvas> transform = canvas => { };
switch (codec.EncodedOrigin)
{
case SKEncodedOrigin.TopLeft:
break;
case SKEncodedOrigin.TopRight:
// flip along the x-axis
transform = canvas => canvas.Scale(-1, 1, useWidth / 2, useHeight / 2);
break;
case SKEncodedOrigin.BottomRight:
transform = canvas => canvas.RotateDegrees(180, useWidth / 2, useHeight / 2);
break;
case SKEncodedOrigin.BottomLeft:
// flip along the y-axis
transform = canvas => canvas.Scale(1, -1, useWidth / 2, useHeight / 2);
break;
case SKEncodedOrigin.LeftTop:
useWidth = original.Height;
useHeight = original.Width;
transform = canvas =>
{
// Rotate 90
canvas.RotateDegrees(90, useWidth / 2, useHeight / 2);
canvas.Scale(useHeight * 1.0f / useWidth, -useWidth * 1.0f / useHeight, useWidth / 2, useHeight / 2);
};
break;
case SKEncodedOrigin.RightTop:
useWidth = original.Height;
useHeight = original.Width;
transform = canvas =>
{
// Rotate 90
canvas.RotateDegrees(90, useWidth / 2, useHeight / 2);
canvas.Scale(useHeight * 1.0f / useWidth, useWidth * 1.0f / useHeight, useWidth / 2, useHeight / 2);
};
break;
case SKEncodedOrigin.RightBottom:
useWidth = original.Height;
useHeight = original.Width;
transform = canvas =>
{
// Rotate 90
canvas.RotateDegrees(90, useWidth / 2, useHeight / 2);
canvas.Scale(-useHeight * 1.0f / useWidth, useWidth * 1.0f / useHeight, useWidth / 2, useHeight / 2);
};
break;
case SKEncodedOrigin.LeftBottom:
useWidth = original.Height;
useHeight = original.Width;
transform = canvas =>
{
// Rotate 90
canvas.RotateDegrees(90, useWidth / 2, useHeight / 2);
canvas.Scale(-useHeight * 1.0f / useWidth, -useWidth * 1.0f / useHeight, useWidth / 2, useHeight / 2);
};
break;
}
var info = new SKImageInfo(useWidth, useHeight);
using (var surface = SKSurface.Create(info))
{
using (var paint = new SKPaint())
{
// high quality with antialiasing
paint.IsAntialias = true;
paint.FilterQuality = SKFilterQuality.High;
// rotate according to origin
transform.Invoke(surface.Canvas);
// draw the bitmap to fill the surface
surface.Canvas.DrawBitmap(original, info.Rect, paint);
surface.Canvas.Flush();
using (SKImage image = surface.Snapshot())
{
return image.Encode(SKEncodedImageFormat.Jpeg, Quality).ToArray();
}
}
}
}
}
}
}
}
}

zxing barcode not displaying any text

I made Barcode generator using ZXing Library but when barcode generate then it wont display text below barcode like
try {
Map<EncodeHintType, Object> hints = null;
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "ABC-abc-1234");
BitMatrix bitMatrix = new Code128Writer().encode("ABC-abc-1234", BarcodeFormat.CODE_128, 350, 150, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
int[] pixels = new int[width * height];
// All are 0, or black, by default
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = bitMatrix.get(x, y) ? Color.BLACK : Color.WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
mImageView.setImageBitmap(bitmap);
} catch (Exception e) {
// TODO: handle exception
}
Maybe it's late to help you but I went through the same problem and was able to solve the following in a C#
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.CODE_128,
Options = new EncodingOptions
{
Height = 160,
Width = 300,
Margin = 0,
PureBarcode = false
},
Renderer = new BitmapRenderer()
{
TextFont = new Font(FontFamily.GenericSerif, 15)
}
};
var bitmap = barcodeWriter.Write("your content");
bitmap.Save(#"C:\\FULL\PATH\FILE.JPG");

Extract of image of "FLATEDECODE" type from pdf using PdfSharp

Im trying to extract images from a pdf. Image is of filter "FlateDecode". Im getting the image but its just a black path. Im a newbie into this, Please help me on this. The code is :
int width = xObject.Elements.GetInteger(PdfImage.Keys.Width);
int height = xObject.Elements.GetInteger(PdfImage.Keys.Height);
int bitsPerComponent = xObject.Elements.GetInteger (PdfSharp.Pdf.Advanced.PdfImage.Keys.BitsPerComponent);
System.Drawing.Imaging.PixelFormat pixelFormat = new System.Drawing.Imaging.PixelFormat();
switch (bitsPerComponent)
{
case 1:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format1bppIndexed;
break;
case 8:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format8bppIndexed;
break;
case 24:
pixelFormat = System.Drawing.Imaging.PixelFormat.Format24bppRgb;
break;
default:
throw new Exception("Unknown pixel format " + bitsPerComponent);
}
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
byte[] raw = xObject.Stream.Value;
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
Marshal.Copy(raw, 0, bitmapData.Scan0, raw.Length);
bitmap.UnlockBits(bitmapData);
using (MemoryStream imageStream = new MemoryStream())
{
bitmap.Save(imageStream, ImageFormat.png);
System.Drawing.Image img = System.Drawing.Image.FromStream(imageStream);
img.Save("D:\\trial.png", System.Drawing.Imaging.ImageFormat.png);
}
img.Save("D:\\trial.png", System.Drawing.Imaging.ImageFormat.Jpeg);
Should that not be .Png?
I have done this using iTextSharp. Following is the code I have done for [filter.Equals(PdfName.FLATEDECODE)] this image.
add using System.Runtime.InteropServices; to access Marshal
Bitmap bmp = new Bitmap(width, height, pixelFormat);
var bmd = bmp.LockBits(new System.Drawing.Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
int length = (int)Math.Ceiling(Convert.ToInt32(width) * i_bpp / 8.0);
for (int j = 0; j < height; j++)
{
int offset = j * length;
int scanOffset = j * bmd.Stride;
Marshal.Copy(bytes, offset, new IntPtr(bmd.Scan0.ToInt32() + scanOffset), length);
}
bmp.UnlockBits(bmd);
using (FileStream fs = new FileStream(Server.MapPath("~/Temp") + "\\" + String.Format("Image{0}.png", page_i), FileMode.Create, FileAccess.Write))
{
bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
PdfImg_ = (System.Drawing.Image)bmp;
}

Resources