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/OAAHFbQeuohJN8bCdwmu8RsIyzhKdnm4gNb8HwXcoILW2dOIbdTfOOA7BeOw2TilfYZjzHIcgozJKYunoiKFltZ6eno7aWqXI93/J8EcVNBq2nNxTP6IkKzN5JR4kdMSxAnbPdw7ez177fYQW2xIQOpekvNcCcu0JDcvlN6u/3vADSpo5U3ZlNR4UNUcTEqVITaqr1m6ez33z9vL3zevIK78IL7p2zgVuhiHmKW4hK8jKNGE+sbiX2lct4DZ2dFJd/f/f6AOCmiNHQVkVDgRVWpGaPYeTqsXcjzkFVYav8Fyw93sMFYx7/1PsHT7mpQGc6Ly92LsPZ/d7k9xxG0RpZpfsp6+vj7y8/KJU8eRnJhCamoqKSkpJCcna48/vVY+z83JJS83n8L8QsrLy6mqqKZapL6ujsb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kL8otITU4jIlxaRwMC8Pf30+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 :)
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
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.
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;
}
I have created an Encryption method to encrypt the data into test.txt Text file. The encryption is Working fine and its Reading the encryted text file into textBox1.
I m using 2 buttons and 2 textBox for doing this.
Now I want to Read the decryption text from test.txt in textBox2
but when i click on the button to read data from test.txt to textBox2.
I am getting an exception like (CryptographicException was unhandled) Bad Data.
Here is the code I used for Dycryption.
private void button2_Click(object sender, EventArgs e)
{
FileStream stream = new FileStream("C:\\test.txt",
FileMode.Open, FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(crStream);
//string data = reader.ReadToEnd();
textBox2.Text = reader.ReadLine();
//stream.Close();
}
Codes that i used for Encrytion is here:
private void button1_Click(object sender, EventArgs e)
{
FileStream stream = new FileStream("C:\\test.txt", FileMode.OpenOrCreate, FileAccess.Write);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateEncryptor(), CryptoStreamMode.Write);
byte[] data = ASCIIEncoding.ASCII.GetBytes(textBox2.Text);
crStream.Write(data, 0, data.Length);
crStream.Close();
stream.Close();
string text = System.IO.File.ReadAllText(#"C://test.txt");
textBox1.Text = text.ToString();
}
I don't know why you want to read it from test.txt file. when your displaying it in textbox. but check below code you can able to encrypt and decry-pt and meanwhile able to display and save in text boxes.
protected void Button1_Click(object sender, EventArgs e)
{
FileStream stream = new FileStream("C:\\test.txt", FileMode.OpenOrCreate, FileAccess.Write);
string datastring= Encrypt("ABCDEFGH", "ABCDEFGH");
byte[] data = ASCIIEncoding.ASCII.GetBytes(datastring);
stream.Write(data, 0, data.Length);
stream.Close();
string text = System.IO.File.ReadAllText(#"C:\\test.txt");
TextBox1.Text = text.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
StreamReader reader =null;
try
{
FileStream stream = new FileStream("C:\\test.txt",
FileMode.Open, FileAccess.Read);
string fileContents;
using ( reader = new StreamReader(stream))
{
fileContents = reader.ReadToEnd();
}
string data = Decrypt(fileContents, "ABCDEFGH");
TextBox2.Text = data;
stream.WriteByte(Convert.ToByte(data));
stream.Close();
}
catch (Exception ex)
{
}
finally
{
reader.Close();
}
}
public static string Encrypt(string message, string password)
{
// Encode message and password
byte[] messageBytes = ASCIIEncoding.ASCII.GetBytes(message);
byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(password);
// Set encryption settings -- Use password for both key and init. vector
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, passwordBytes);
CryptoStreamMode mode = CryptoStreamMode.Write;
// Set up streams and encrypt
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(messageBytes, 0, messageBytes.Length);
cryptoStream.FlushFinalBlock();
// Read the encrypted message from the memory stream
byte[] encryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
// Encode the encrypted message as base64 string
string encryptedMessage = Convert.ToBase64String(encryptedMessageBytes);
return encryptedMessage;
}
public static string Decrypt(string encryptedMessage, string password)
{
// Convert encrypted message and password to bytes
byte[] encryptedMessageBytes = Convert.FromBase64String(encryptedMessage);
byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(password);
// Set encryption settings -- Use password for both key and init. vector
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, passwordBytes);
CryptoStreamMode mode = CryptoStreamMode.Write;
// Set up streams and decrypt
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
cryptoStream.FlushFinalBlock();
// Read decrypted message from memory stream
byte[] decryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);
// Encode deencrypted binary data to base64 string
string message = ASCIIEncoding.ASCII.GetString(decryptedMessageBytes);
return message;
}
I am working on implementing a SAMLSLO through HTTP-REDIRECT binding mechanism. Using deflate-inflate tools gives me a DataFormatException with incorrect header check.
I tried this as a stand-alone. Though I did not get DataFormatException here I observed the whole message is not being returned.
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class InflateDeflate {
public static void main(String[] args) {
String source = "This is the SAML String";
String outcome=null;
byte[] bytesource = null;
try {
bytesource = source.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int byteLength = bytesource.length;
Deflater compresser = new Deflater();
compresser.setInput(bytesource);
compresser.finish();
byte[] output = new byte[byteLength];
int compressedDataLength = compresser.deflate(output);
outcome = new String(output);
String trimmedoutcome = outcome.trim();
//String trimmedoutcome = outcome; // behaves the same way as trimmed;
// Now try to inflate it
Inflater decompresser = new Inflater();
decompresser.setInput(trimmedoutcome.getBytes());
byte[] result = new byte[4096];
int resultLength = 0;
try {
resultLength = decompresser.inflate(result);
} catch (DataFormatException e) {
e.printStackTrace();
}
decompresser.end();
System.out.println("result length ["+resultLength+"]");
String outputString = null;
outputString = new String(result, 0, resultLength);
String returndoc = outputString;
System.out.println(returndoc);
}
}
Surprisingly I get the result as [22] bytes, the original is [23] bytes and the 'g' is missing after inflating.
Am I doing something fundamentally wrong here?
Java's String is a CharacterSequence (a character is 2 bytes). Using new String(byte[]) may not correctly convert your byte[] to a String representation. At least you should specify a character encoding new String(byte[], "UTF-8") to prevent invalid character conversions.
Here's an example of compressing and decompressing:
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;
...
byte[] sourceData; // bytes to compress (reuse byte[] for compressed data)
String filename; // where to write
{
// compress the data
Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION);
deflater.setInput(sourceData);
deflater.finish();
int compressedSize = deflater.deflate(data, 0, sourceData.length, Deflater.FULL_FLUSH);
// write the data
OutputStream stream = new FileOutputStream(filename);
stream.write(data, 0, compressedSize);
stream.close();
}
{
byte[] uncompressedData = new byte[1024]; // where to store the data
// read the data
InputStream stream = new InflaterInputStream(new FileInputStream(filename));
// read data - note: may not read fully (or evenly), read from stream until len==0
int len, offset = 0;
while ((len = stream.read(uncompressedData , offset, uncompressedData .length-offset))>0) {
offset += len;
}
stream.close();
}