Edit :
Sorry for the late response.
I tried the code in the answer ,but I had a problem with the conversion from Byte to Image .
public override void ViewDidLoad()
{
var image = UIImage.FromFile("image.png");
var imageWidth = image.Size.Width;
var imageHeight = image.Size.Height;
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullfilename = Path.Combine(documents, "Image.json");
// save json methode
SaveImageJson(image, fullfilename);
// read json methode
var newImage = readImageJson(fullfilename, imageWidth, imageHeight);
}
public static void SaveImageJson(UIImage image, string fullfilename)
{
// Convert image to byteArray
Byte[] imageByteArray = ReadFully(image.AsPNG().AsStream());
// Serialize object
var json = JsonConvert.SerializeObject(imageByteArray, Formatting.Indented);
// Save to file
File.WriteAllText(fullfilename, json);
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
public static UIImage readImageJson(string fullfilename, nfloat width, nfloat height)
{
var filenameNewImage = File.ReadAllText(fullfilename, System.Text.Encoding.ASCII);
var jsonNewImage = JsonConvert.DeserializeObject(filenameNewImage);
Byte[] ByteNewImage = ObjectToByteArray(jsonNewImage);
UIImage NewImage = new UIImage();
NewImage = ImageFromBytes(ByteNewImage, width, height);
return NewImage;
}
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
private static UIImage ImageFromBytes(byte[] bytes, nfloat width, nfloat height)
{
try
{
NSData data = NSData.FromArray(bytes);
UIImage image = UIImage.LoadFromData(data);
CGSize scaleSize = new CGSize(width, height);
UIGraphics.BeginImageContextWithOptions(scaleSize, false, 0);
image.Draw(new CGRect(0, 0, scaleSize.Width, scaleSize.Height));
UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return resizedImage;
}
catch (Exception)
{
return null;
}
}
I have a problem converting an Object to a Byte Array
I have a Xamarin.IOS simulation in which I have to read the data which is an image that i saved before using the Json method . I have a problem while reading my data back and I think it has a relation with the conversion . I used a method to convert the object that I get from the Json file to an Byte Array, so I can convert that later to an UIImage , unfortunately the conversion doesn't work because when I compare the Byte Array I saved and the one I got from method read , I found out that they are different
public override void ViewDidLoad()
{
base.ViewDidLoad();
// getting the file that we saved the data before
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, "account.json");
File.WriteAllText(filename, json);
var filename2 = File.ReadAllText(filename,System.Text.Encoding.ASCII);
var json2 = ObjectToByteArray(JsonConvert.DeserializeObject(filename2));
NSData data2 = NSData.FromArray(json2);
UIImage image2 = new UIImage();
image2 = UIImage.LoadFromData(data2);
img.Image = image2;
}
public static byte[] ObjectToByteArray(Object obj)
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
Use another conversion.
First of all, convert your UIImage to Stream. To do it use 'myUIImage.AsPng().AsStream()'. Then convert 'Stream' to 'Byte Array'. To do so use:
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16*1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Then you can safely serialize it.
To make Image from Byte Array you can use this extension
private UIImage ImageFromBytes(byte[] bytes, nfloat width, nfloat height)
{
try {
NSData data = NSData.FromArray(bytes);
UIImage image = UIImage.LoadFromData(data);
CGSize scaleSize = new CGSize(width, height);
UIGraphics.BeginImageContextWithOptions(scaleSize, false, 0);
image.Draw(new CGRect(0,0, scaleSize.Width, scaleSize.Height));
UIImage resizedImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return resizedImage;
} catch (Exception) {
return null;
}
}
Believe this will be helpful.
Related
Hello am new to Android studio
I have made recylerview for transaction details . I need to create pdf for this recylerview items.
Example: I have 24 cardviews in recylerview so need to create pdf with each page 4 cardviews only . So totally I need to get pdf as 6 pages .
How to do that . Thanks in advance.
This is sample image of my view
Am passing below code
recyclerView.measure(View.MeasureSpec.makeMeasureSpec(recyclerView.getWidth(),View.MeasureSpec.EXACTLY),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED));
Bitmap bm=Bitmap.createBitmap(recyclerView.getWidth(),recyclerView.getMeasuredHeight(),Bitmap.Config.ARGB_8888);
String mpath2="/mnt/sdcard/mathanpaymentpdf";
File imageFile = new File(mpath2);
PDFHelper pdfHelper = new PDFHelper(imageFile,this);
pdfHelper.saveImageToPDF(recyclerView,bm,"mathan"+System.currentTimeMillis());
public class PDFHelper {
private File mFolder;
private File mFile;
private Context mContext;
public PDFHelper(File folder, Context context) {
this.mContext = context;
this.mFolder = folder;
if(!mFolder.exists())
mFolder.mkdirs();
}
public void saveImageToPDF(View title, Bitmap bitmap, String filename) {
mFile = new File(mFolder, filename + ".pdf");
if (!mFile.exists()) {
int height = title.getHeight() + bitmap.getHeight();
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), height, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
title.draw(canvas);
canvas.drawBitmap(bitmap, null, new Rect(0, title.getHeight(), bitmap.getWidth(),bitmap.getHeight()), null);
document.finishPage(page);
try {
mFile.createNewFile();
OutputStream out = new FileOutputStream(mFile);
document.writeTo(out);
document.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This am tried am getting pdf on a single page only
Just I need to split into multiple pages.
Note: I need code in java, not in kotlin
Am solved this by using itext library
implementation 'com.itextpdf:itextpdf:5.0.6'
Then call with RecylerView
public void generatePDF(RecyclerView view) {
RecyclerView.Adapter adapter = view.getAdapter();
int sie2=adapter.getItemCount();
if (sie2 == 0) {
Toast.makeText(this,"No Transactions",Toast.LENGTH_LONG).show();
}else{
Bitmap bigBitmap = null;
if (adapter != null) {
int size = adapter.getItemCount();
int height = 0;
Paint paint = new Paint();
int iHeight = 0;
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
LruCache<String, Bitmap> bitmaCache = new LruCache<>(cacheSize);
for (int i = 0; i < size; i++) {
RecyclerView.ViewHolder holder = adapter.createViewHolder(view, adapter.getItemViewType(i));
adapter.onBindViewHolder(holder, i);
holder.itemView.measure(View.MeasureSpec.makeMeasureSpec(view.getWidth(), View.MeasureSpec.EXACTLY),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
holder.itemView.layout(0, 0, holder.itemView.getMeasuredWidth(), holder.itemView.getMeasuredHeight());
holder.itemView.setDrawingCacheEnabled(true);
holder.itemView.buildDrawingCache();
Bitmap drawingCache = holder.itemView.getDrawingCache();
if (drawingCache != null) {
bitmaCache.put(String.valueOf(i), drawingCache);
}
height += holder.itemView.getMeasuredHeight();
}
bigBitmap = Bitmap.createBitmap(view.getMeasuredWidth(), height, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
bigCanvas.drawColor(Color.WHITE);
Document document=new Document();
final File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "MAT"+System.currentTimeMillis()+".pdf");
try {
PdfWriter.getInstance(document, new FileOutputStream(file));
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
}
for (int i = 0; i < size; i++) {
try {
//Adding the content to the document
Bitmap bmp = bitmaCache.get(String.valueOf(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
com.itextpdf.text.Image image= com.itextpdf.text.Image.getInstance(stream.toByteArray());
//Image image = Image.getInstance(stream.toByteArray());
float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
- document.rightMargin() - 50) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
image.scalePercent(scaler);
image.setAlignment(com.itextpdf.text.Image.ALIGN_CENTER | com.itextpdf.text.Image.ALIGN_TOP);
if (!document.isOpen()) {
document.open();
}
document.add(image);
} catch (Exception ex) {
Log.e("TAG-ORDER PRINT ERROR", ex.getMessage());
}
}
if (document.isOpen()) {
document.close();
}
// Set on UI Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(MainActivityAdminMain.this);
builder.setTitle("Success")
.setMessage("PDF File Generated Successfully.")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("Open", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// dialog.dismiss();
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), "application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent56 = Intent.createChooser(target, "Open File");
try {
startActivity(intent56);
} catch (ActivityNotFoundException e) {
Toast.makeText(MainActivityAdminMain.this,"No PDF Viewer Installed.",Toast.LENGTH_LONG).show();
}
}
}).show();
}
});
}}
}
100% working.. This helps to anyone needs
Hi I want to convert Stream to Byte and for this I am using the below code for converting.
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var imageSrc = new BitmapImage();
imageSrc.SetSource(e.ChosenPhoto);
imgUploadedInsurance.Source = imageSrc;
_BitmapImage.SetSource(e.ChosenPhoto);
image = Converter.StreamToByte(e.ChosenPhoto);
}
}
Below method is used for converting which is returning 0 byte
public static byte[] StreamToByte(Stream input)
{
//byte[] buffer = new byte[16 * 1024];
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
// input.CopyTo(ms);
return ms.ToArray();
}
}
You souldn't return ms.ToArray(), but buffer. Here's my version of the method that will work:
public static byte[] StreamToByte(Stream input)
{
byte[] buffer = new byte[input.Length];
input.Read(buffer, 0, buffer.Length);
return buffer;
}
Note: Giving the background of my previous question once again so as to find all the related stuff at one source.
I'm capturing an image from an android mobile device and it’s in JPEG format. The image is of 72X72DPI and 24 bit. When I try to convert this JPEG image to TIFF using LibTiff.Net and to set the tag Photometric Interpretation = 0 for MinIsWhite, the image turns negative (the white becomes black and black becomes white). The environment is Windows 8.1 64 bit, Visual Studio 2012. The tag must have value 0, where 0 = white is zero.
I absolutely must use Photometric.MINISWHITE in images so tried inverting image data before writing it to TIFF as per the below code. But then the compression changes to LZW instead of CCITT4,Photometric is changed to MINISBLACK from MINISWHITE, FIllorder tag is removed, PlanarConfig tag is removed, New tag Predictor is added with value 1 and the image turns negative again.
public partial class Form1 : Form
{
private const TiffTag TIFFTAG_ASCIITAG = (TiffTag)666;
private const TiffTag TIFFTAG_LONGTAG = (TiffTag)667;
private const TiffTag TIFFTAG_SHORTTAG = (TiffTag)668;
private const TiffTag TIFFTAG_RATIONALTAG = (TiffTag)669;
private const TiffTag TIFFTAG_FLOATTAG = (TiffTag)670;
private const TiffTag TIFFTAG_DOUBLETAG = (TiffTag)671;
private const TiffTag TIFFTAG_BYTETAG = (TiffTag)672;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (Bitmap bmp = new Bitmap(#"D:\Projects\ITests\images\IMG_2.jpg"))
{
// convert jpg image to tiff
byte[] tiffBytes = GetTiffImageBytes(bmp, false);
File.WriteAllBytes(#"D:\Projects\ITests\images\output.tif", tiffBytes);
//Invert the tiff image
Bitmap bmpTiff = new Bitmap(#"D:\Projects\ITests\images\output.tif");
Bitmap FBitmap = Transform(bmpTiff);
FBitmap.Save(#"D:\Projects\ITests\images\invOutput1.tif");
}
}
public static byte[] GetTiffImageBytes(Bitmap img, bool byScanlines)
{
try
{
byte[] raster = GetImageRasterBytes(img);
using (MemoryStream ms = new MemoryStream())
{
using (Tiff tif = Tiff.ClientOpen("InMemory", "w", ms, new TiffStream()))
{
if (tif == null)
return null;
tif.SetField(TiffTag.IMAGEWIDTH, img.Width);
tif.SetField(TiffTag.IMAGELENGTH, img.Height);
tif.SetField(TiffTag.COMPRESSION, Compression.CCITTFAX4);
tif.SetField(TiffTag.PHOTOMETRIC, Photometric.MINISWHITE);
tif.SetField(TiffTag.ROWSPERSTRIP, img.Height);
tif.SetField(TiffTag.XRESOLUTION, 200);
tif.SetField(TiffTag.YRESOLUTION, 200);
tif.SetField(TiffTag.SUBFILETYPE, 0);
tif.SetField(TiffTag.BITSPERSAMPLE, 1);
tif.SetField(TiffTag.FILLORDER, FillOrder.LSB2MSB);
tif.SetField(TiffTag.ORIENTATION, BitMiracle.LibTiff.Classic.Orientation.TOPLEFT);
tif.SetField(TiffTag.SAMPLESPERPIXEL, 1);
tif.SetField(TiffTag.RESOLUTIONUNIT, ResUnit.INCH);
tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
int tiffStride = tif.ScanlineSize();
int stride = raster.Length / img.Height;
if (byScanlines)
{
// raster stride MAY be bigger than TIFF stride (due to padding in raster bits)
for (int i = 0, offset = 0; i < img.Height; i++)
{
bool res = tif.WriteScanline(raster, offset, i, 0);
if (!res)
return null;
offset += stride;
}
}
else
{
if (tiffStride < stride)
{
// raster stride is bigger than TIFF stride
// this is due to padding in raster bits
// we need to create correct TIFF strip and write it into TIFF
byte[] stripBits = new byte[tiffStride * img.Height];
for (int i = 0, rasterPos = 0, stripPos = 0; i < img.Height; i++)
{
System.Buffer.BlockCopy(raster, rasterPos, stripBits, stripPos, tiffStride);
rasterPos += stride;
stripPos += tiffStride;
}
// Write the information to the file
int n = tif.WriteEncodedStrip(0, stripBits, stripBits.Length);
if (n <= 0)
return null;
}
else
{
// Write the information to the file
int n = tif.WriteEncodedStrip(0, raster, raster.Length);
if (n <= 0)
return null;
}
}
}
return ms.GetBuffer();
}
}
catch (Exception)
{
return null;
}
}
public static byte[] GetImageRasterBytes(Bitmap img)
{
// Specify full image
Rectangle rect = new Rectangle(0, 0, img.Width, img.Height);
Bitmap bmp = img;
byte[] bits = null;
try
{
// Lock the managed memory
if (img.PixelFormat != PixelFormat.Format1bppIndexed)
bmp = convertToBitonal(img);
BitmapData bmpdata = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format1bppIndexed);
// Declare an array to hold the bytes of the bitmap.
bits = new byte[bmpdata.Stride * bmpdata.Height];
// Copy the sample values into the array.
Marshal.Copy(bmpdata.Scan0, bits, 0, bits.Length);
// Release managed memory
bmp.UnlockBits(bmpdata);
}
finally
{
if (bmp != img)
bmp.Dispose();
}
return bits;
}
private static Bitmap convertToBitonal(Bitmap original)
{
int sourceStride;
byte[] sourceBuffer = extractBytes(original, out sourceStride);
// Create destination bitmap
Bitmap destination = new Bitmap(original.Width, original.Height,
PixelFormat.Format1bppIndexed);
destination.SetResolution(original.HorizontalResolution, original.VerticalResolution);
// Lock destination bitmap in memory
BitmapData destinationData = destination.LockBits(
new Rectangle(0, 0, destination.Width, destination.Height),
ImageLockMode.WriteOnly, PixelFormat.Format1bppIndexed);
// Create buffer for destination bitmap bits
int imageSize = destinationData.Stride * destinationData.Height;
byte[] destinationBuffer = new byte[imageSize];
int sourceIndex = 0;
int destinationIndex = 0;
int pixelTotal = 0;
byte destinationValue = 0;
int pixelValue = 128;
int height = destination.Height;
int width = destination.Width;
int threshold = 500;
for (int y = 0; y < height; y++)
{
sourceIndex = y * sourceStride;
destinationIndex = y * destinationData.Stride;
destinationValue = 0;
pixelValue = 128;
for (int x = 0; x < width; x++)
{
// Compute pixel brightness (i.e. total of Red, Green, and Blue values)
pixelTotal = sourceBuffer[sourceIndex + 1] + sourceBuffer[sourceIndex + 2] +
sourceBuffer[sourceIndex + 3];
if (pixelTotal > threshold)
destinationValue += (byte)pixelValue;
if (pixelValue == 1)
{
destinationBuffer[destinationIndex] = destinationValue;
destinationIndex++;
destinationValue = 0;
pixelValue = 128;
}
else
{
pixelValue >>= 1;
}
sourceIndex += 4;
}
if (pixelValue != 128)
destinationBuffer[destinationIndex] = destinationValue;
}
Marshal.Copy(destinationBuffer, 0, destinationData.Scan0, imageSize);
destination.UnlockBits(destinationData);
return destination;
}
private static byte[] extractBytes(Bitmap original, out int stride)
{
Bitmap source = null;
try
{
// If original bitmap is not already in 32 BPP, ARGB format, then convert
if (original.PixelFormat != PixelFormat.Format32bppArgb)
{
source = new Bitmap(original.Width, original.Height, PixelFormat.Format32bppArgb);
source.SetResolution(original.HorizontalResolution, original.VerticalResolution);
using (Graphics g = Graphics.FromImage(source))
{
g.DrawImageUnscaled(original, 0, 0);
}
}
else
{
source = original;
}
// Lock source bitmap in memory
BitmapData sourceData = source.LockBits(
new Rectangle(0, 0, source.Width, source.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// Copy image data to binary array
int imageSize = sourceData.Stride * sourceData.Height;
byte[] sourceBuffer = new byte[imageSize];
Marshal.Copy(sourceData.Scan0, sourceBuffer, 0, imageSize);
// Unlock source bitmap
source.UnlockBits(sourceData);
stride = sourceData.Stride;
return sourceBuffer;
}
finally
{
if (source != original)
source.Dispose();
}
}
public Bitmap Transform(Bitmap bitmapImage)
{
var bitmapRead = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
var bitmapLength = bitmapRead.Stride * bitmapRead.Height;
var bitmapBGRA = new byte[bitmapLength];
Marshal.Copy(bitmapRead.Scan0, bitmapBGRA, 0, bitmapLength);
bitmapImage.UnlockBits(bitmapRead);
for (int i = 0; i < bitmapLength; i += 4)
{
bitmapBGRA[i] = (byte)(255 - bitmapBGRA[i]);
bitmapBGRA[i + 1] = (byte)(255 - bitmapBGRA[i + 1]);
bitmapBGRA[i + 2] = (byte)(255 - bitmapBGRA[i + 2]);
// [i + 3] = ALPHA.
}
var bitmapWrite = bitmapImage.LockBits(new Rectangle(0, 0, bitmapImage.Width, bitmapImage.Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb);
Marshal.Copy(bitmapBGRA, 0, bitmapWrite.Scan0, bitmapLength);
bitmapImage.UnlockBits(bitmapWrite);
return bitmapImage;
}
}
You should invert image bytes in GetTiffImageBytes method, before writing them to TIFF. Also, the Transform method converts bi-level image to 32bpp one and that is why you get LZW compressed image in the end.
So, add the following code
for (int k = 0; k < raster.Length; k++)
raster[k] = (byte)(~raster[k]);
after byte[] raster = GetImageRasterBytes(img); in GetTiffImageBytes method. This will invert image bytes. And don't use the following code
//Invert the tiff image
Bitmap bmpTiff = new Bitmap(#"D:\Projects\ITests\images\output.tif");
Bitmap FBitmap = Transform(bmpTiff);
FBitmap.Save(#"D:\Projects\ITests\images\invOutput1.tif");
I want to convert base64string to bitmap and i m doing below method but its not working.
public static BitmapImage base64image(string s)
{
if (s.Length > 0)
{
byte[] fileBytes = Convert.FromBase64String(s.Trim('\0'));
// byte[] fileBytes = new byte[s.Length * sizeof(char)];
//System.Buffer.BlockCopy(s.ToCharArray(), 0, fileBytes, 0, fileBytes.Length);
using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
{
ms.Write(fileBytes, 0, fileBytes.Length);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(ms);
return bitmapImage;
}
}
else
{
return null;
}
}
my base64 string is
string s="iVBORw0KGgoAAAANSUhEUgAAAE0AAABACAYAAABfl/puAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAgY0hSTQAAeiYAAICEAAD6AAAAgOgAAHUwAADqYAAAOpgAABdwnLpRPAAAH1pJREFUeF7tmwd4VVXW95NQVWyIioiMCljHCmJBEVFERVCs4FhwHMCCAkoNivTeAgFSSCUhkEZI7z03yU3vvSc3vff6e9e5eVUYFcIY5/veeWY/z3rOLeeee/b/rPrfa+v29va66erq3qXz3zFwBHp6eor477giBHQEtIwr+sV/T+ZPAa23u/c/GtpBB62ru4rs0iAKKtQ0NGgEvL7/OAAHFbQeuohJN8bCd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CURWNFw7ql+ldSlStddL4cwgMCrbuzWzYl1Mqm1DzpF4uTlqQA6QBywtrSgkP7NrPl2/kcWH0/NtvH4HhYWQwZImarJ6IrQOr1i6ly1JXgIGWRkQ5Oh0ZiuWUMh9fezvY1Czi4fws2tqdxdXWX9qdA2Z8Zq93HWS/R8FI77JRNGg2yAVYj3T3KHk2lny0iQvrQpIUqMlJNgjTE5EtUrZTU43IbOi4H1k/fDwi0LrkxZSdHZnYO0TKZAOnjcnBwwPTkSQ4dPsbWzZtZ880nrFo6hw3LHmDHyjs5sno0x/Rv4timsRz74VaO/zCWo+tu4MA3I9nxza2sW/4sK5bNZ8M3C9m+bQcGR42wsLTEWcqfAOkLU8claHtv66QPo0cIzt8bikYpG2kL8otITU4jIlxaRwMC8Pf30+4yUcv9pmdm94PWT/z94TEg0JR/UZ52a0ur9LZWa7dBx8vu3GBpjPOUxdkzZ+0xNbPikIEhe7f/wM7vv2Drmnf5/tv30F+5AP0Vb7Jx1dva95tXL2L3phXs2fEjhseMMLewxt7eQds8FxEaLlt8krUtBXWSXykbJQZqnj1ixj093dpddIpGKfsTFFHe9w7YxAeG54BBu/Byyv7vLtmR1i5b+xoapM9VqJiS4mJyZLKpadnC7+cSm5BKlPSeRUXF/q/EielIv6t8npyaRnp6FgXZ+ZRIkqs8CGVHcafsE1X80YUNdAObxr/3LAW0wacB/r1z+Lf/mwLa4C0I/ttv///NH/4PGV2zXGJJhfQAAAAASUVORK5CYII="
But it gives an exception like "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
How can i solve this problem?
Try this:
public void ConvertThis(string ImageText)
{
if (ImageText.Length > 0)
{
Byte[] bitmapData = new Byte[ImageText.Length];
bitmapData = Convert.FromBase64String(FixBase64ForImage(ImageText));
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
Bitmap bitImage = new Bitmap((Bitmap)Image.FromStream(streamBitmap));
}
}
public string FixBase64ForImage(string Image)
{
System.Text.StringBuilder sbText = new System.Text.StringBuilder(Image,Image.Length);
sbText.Replace("\r\n", String.Empty);
sbText.Replace(" ", String.Empty);
return sbText.ToString();
}
hope it helps :)
I'm using Speex to encode the raw data but after I decode the data the audio plays at a faster rate because it makes you sound like a chipmunk. I'm using NSpeex and Silverlight 4.
8kHz Sampling
Encoding Function:
JSpeexEnc encoder = new JSpeexEnc();
int rawDataSize = 0;
public byte[] EncodeAudio(byte[] rawData)
{
var encoder = new SpeexEncoder(BandMode.Narrow);
var inDataSize = rawData.Length / 2;
var inData = new short[inDataSize];
for (var index = 0; index < rawData.Length; index += 2)
{
inData[index / 2] = BitConverter.ToInt16(rawData, index);
}
inDataSize = inDataSize - inDataSize % encoder.FrameSize;
var encodedData = new byte[rawData.Length];
var encodedBytes = encoder.Encode(inData, 0, inDataSize, encodedData, 0, encodedData.Length);
byte[] encodedAudioData = null;
if (encodedBytes != 0)
{
encodedAudioData = new byte[encodedBytes];
Array.Copy(encodedData, 0, encodedAudioData, 0, encodedBytes);
}
rawDataSize = inDataSize; // Count of encoded shorts, for debugging
return encodedAudioData;
}
Decoding Function:
SpeexDecoder decoder = new SpeexDecoder(BandMode.Narrow);
public byte[] Decode(byte[] encodedData)
{
try
{
short[] decodedFrame = new short[8000]; // should be the same number of samples as on the capturing side
int decoderBytes = decoder.Decode(encodedData, 0, encodedData.Length, decodedFrame, 0, false);
byte[] decodedData = new byte[encodedData.Length];
byte[] decodedAudioData = null;
decodedAudioData = new byte[decoderBytes * 2];
for (int shortIndex = 0, byteIndex = 0; byteIndex < decoderBytes; shortIndex++)
{
BitConverter.GetBytes(decodedFrame[shortIndex + byteIndex]).CopyTo(decodedAudioData, byteIndex * 2);
byteIndex++;
}
// todo: do something with the decoded data
return decodedAudioData;
}
catch (Exception ex)
{
ShowMessageBox(ex.Message.ToString());
return null;
}
}
Playing the audio:
void PlayWave(byte[] PCMBytes)
{
byte[] decodedBuffer = Decode(PCMBytes);
MemoryStream ms_PCM = new MemoryStream(decodedBuffer);
MemoryStream ms_Wave = new MemoryStream();
_pcm.SavePcmToWav(ms_PCM, ms_Wave, 16, 8000, 1);
WaveMediaStreamSource WaveStream = new WaveMediaStreamSource(ms_Wave);
mediaElement1.SetSource(WaveStream);
mediaElement1.Play();
}
Sorry guys for the late response but I figured out what the problem was.
Inside my decode function I loop through the decoded short array but I'm only copying half of the bytes into my new byte array.
It needs to look something like this:
decodedAudioData = new byte[decoderBytes * 2];
for (int shortIndex = 0, byteIndex = 0; shortIndex < decodedFrame.Length; shortIndex++, byteIndex += 2)
{
byte[] temp = BitConverter.GetBytes(decodedFrame[shortIndex]);
decodedAudioData[byteIndex] = temp[0];
decodedAudioData[byteIndex + 1] = temp[1];
}