I am hoping to decompress a zlib file.
Below is a picture of my original:
When byte no 4 is not equal to 0, it needs to decompress after 9th bytes.
After I decompress, I receive the following error:
"java.util.zip.DataFormatException: incorrect header check"
My code is below:
private static void writeToRawInFile(byte[] bData) {
try {
int index = 4;
byteBuffer = null;
byteBuffer = ByteBuffer.allocate(bData.length);
byteBuffer.put(bData);
byteBuffer.flip();
byte[] convertByte = byteBuffer.array();
System.out.println("Byte:" + convertByte.toString());
if (byteBuffer.get(index) == 0) {
System.out.println("index 0");
byteBuffer = null;
byteBuffer = ByteBuffer.allocate(bData.length);
byteBuffer.put(bData);
byteBuffer.flip();
//factoryType.fileServer.fc.write(byteBuffer);
} else {
//bData = Arrays.copyOfRange(bData, 1,9);
bData = decompressByteArray(Arrays.copyOfRange(bData, 0,9));
byteBuffer = ByteBuffer.allocate(bData.length);
byteBuffer.put(bData);
byteBuffer.flip();
System.out.println("data ="+ byteBuffer);
//factoryType.fileServer.fc.write(byteBuffer);
}
//factoryType.fileServer.fc.write(byteBuffer);
} catch (Exception e) {
System.out.println("expMsg .writeToRawInFile()=" + e.getMessage());
e.printStackTrace();
}
if (byteBuffer != null) {
byteBuffer.clear();
}
}
public static byte[] decompressByteArray(byte[] bytes) throws IOException, DataFormatException {
Inflater inflater = new Inflater();
System.out.println("Original: " + bytes.length);
inflater.setInput(bytes);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(bytes.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
System.out.println("Compressed: " + output.length);
return output;
}
Related
I'm trying to compress a Base64 String using the java.util.zip.GZIPInputStream and Deflater clases. My problem is that after compression the size is not less from both cases. For the first case with the GZIPInputStream the size is bigger, and in the second case with the Deflater class the size is almost the same.
The output of my code is:
Original String Size: 8799
CompressedGZip String Size: 8828
UncompressedGZip String Size: 8799
Original_String_Length=8799
Compressed_String_Length Deflater=8812, Compression_Ratio=-0.147%
Decompressed_String_Length Deflater=8799 == Original_String_Length (8799)
Original_String == Decompressed_String=True
As you can see in both cases the compressed string is not less. I need to compress the input base64 String because in some cases is too long. Is there any way to achieve this?
This is my code:
private static String compressFileGZip(String data) {
try {
// Create an output stream, and a gzip stream to wrap over.
ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length());
GZIPOutputStream gzip = new GZIPOutputStream(bos);
// Compress the input string
gzip.write(data.getBytes());
gzip.close();
byte[] compressed = bos.toByteArray();
bos.close();
// Convert to base64
compressed = Base64.getEncoder().encode(compressed);
// return the newly created string
return new String(compressed);
} catch(IOException e) {
return null;
}
}
private static String decompressFileGZip(String compressedText) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// get the bytes for the compressed string
byte[] compressed = compressedText.getBytes("UTF8");
// convert the bytes from base64 to normal string
Base64.Decoder d = Base64.getDecoder();
compressed = d.decode(compressed);
// decode.
final int BUFFER_SIZE = 32;
ByteArrayInputStream is = new ByteArrayInputStream(compressed);
GZIPInputStream gis = new GZIPInputStream(is, BUFFER_SIZE);
StringBuilder string = new StringBuilder();
byte[] data = new byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = gis.read(data)) != -1)
{
string.append(new String(data, 0, bytesRead));
}
gis.close();
is.close();
return string.toString();
}
public static void main(String args[]) {
String input = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxMTEhMTExIVFhUXFxUXFxUYFRUVFRUSFRIXFhUVFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMtNygtLisBCgoKDg0OGxAQGi0lHyUvLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0rNy0tLS0tLS0rK//AABEIAKgBLAMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAEBQIDAAEGBwj/xAA9EAABAwMCAwYDBQgCAQUAAAABAAIRAwQhEjEFQVEGImFxgZETMrEjUpKhwQcUQmJy0eHwM7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Oi7dxtk7W2Lk0oWr3lrKVIv72agDtJqA4EnGBiQibCiRpDWai4xJHdZTB7zjOCeULuzxJhq29NghoY9wEbuGiCI6CQVHNlcWopD44X7mcjwSqGOfSq02u72Q8AierTyPiEdxrsh8dpfau8fgu2nnod6Kvj7B+9vxGxjlkckRZ1XDmQPMhbMcVPGmzNklxm0jz2vavpP0VGOY4fwuBB9OoV7HeK9Xe2jcs+HcaXDlrAcRyw/5m+hXO8X/Zy9oL7Z+tvJpIPoH8vVRy4fw1YM6XZyLnfZlAkyjLijUph1N9NzXDcOEe3XzCXHxWdRrTNU8qdNEnv6KsLYCkHJ+iL2N9Q6j3CnTeAfmHuFixbFIxUMWVw5sEt9wlFeGncGfELFiTJtD4/bLRupSa5uCPcIN1ODEj3WLFmXZpk9F9qBG4x4qyg8dR7hbWJ0QnsKpub94e4VtRzY3HuFixVi9EZITXREnI91pjxG6xYlY6ROlEjPPqnvEhTFEQ5s+Y6LFiMWBoQ0njaQnIYwUtx7hYsXQ8hl4F1GuAIkb9UdVuxpBkYB5jciFixK3o6vcKnvBpuyN+qAdv7rSxKVLqVHVqgjutLiSQPQdVlhSa5wL/kG45u8AtrFwDo7KuKlVpOlrGiGiRATa8tWluHtOfvD+6xYtMPiZsiuQdbUGNaQXs2+83c+q5vjrKNGrrbUD3lpaGYLWbd4kfTxWli6T0GC2J6Fk6qZkQeZIEpsOHCm3U4ggcg4aj4DxWLEkXqwvbC+E2tS+e0mrToW9Jw0jUA7G0NnPifyTP4YpVqYD2wyu4TrB7rg2TM7GVixY0qmbG7gXcTDDcVHB7DhudQ+6gLi4HJ7fxBYsW7C6gkY8sE5tg4vIPzj3Cc8H7UmiR3wWncSIWLE7dixR0/Erayv6OX0w4jB1Ma9h8J+i8a43wl9tVNJ7mujLXtIIe3kR0ONltYs+RGmDYvc5aW1ikUP/9k=";
String compressedGZip = compressFileGZip(input);
String compressedDeflater = null;
String uncompressedGZip = null;
String decompressed = null;
try {
compressedDeflater = compress(input);
uncompressedGZip = decompressFileGZip(compressedGZip);
decompressed = decompress(decodeBase64(compressedDeflater));
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Original String Size: " + input.length());
System.out.println("CompressedGZip String Size: " + compressedGZip.length());
System.out.println("UncompressedGZip String Size: " + uncompressedGZip.length());
Integer savedLength = input.length() - compressedDeflater.length();
Double saveRatio = (new Double(savedLength) * 100) / input.length();
String ratioString = saveRatio.toString() + "00000000";
ratioString = ratioString.substring(0, ratioString.indexOf(".") + 4);
println("Original_String_Length=" + input.length());
println("Compressed_String_Length Deflater=" + compressedDeflater.length() + ", Compression_Ratio=" + ratioString + "%");
println("Decompressed_String_Length Deflater=" + decompressed.length() + " == Original_String_Length (" + input.length() + ")");
println("Original_String == Decompressed_String=" + (input.equals(decompressed) ? "True" : "False"));
// end
}
public static String compress(String str) throws Exception {
return compress(str.getBytes("UTF-8"));
}
public static String compress(byte[] bytes) throws Exception {
Deflater deflater = new Deflater();
deflater.setInput(bytes);
deflater.finish();
//deflater.deflate(bytes, 2, bytes.length);
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
byte[] buffer = new byte[1024];
while(!deflater.finished()) {
int count = deflater.deflate(buffer);
bos.write(buffer, 0, count);
}
bos.close();
byte[] output = bos.toByteArray();
return encodeBase64(output);
}
public static String decompress(byte[] bytes) throws Exception {
Inflater inflater = new Inflater();
inflater.setInput(bytes);
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
bos.write(buffer, 0, count);
}
bos.close();
byte[] output = bos.toByteArray();
return new String(output);
}
public static String encodeBase64(byte[] bytes) throws Exception {
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encodeBuffer(bytes).replace("\r\n", "").replace("\n", "");
}
public static byte[] decodeBase64(String str) throws Exception {
BASE64Decoder base64Decoder = new BASE64Decoder();
return base64Decoder.decodeBuffer(str);
}
public static void println(Object o) {
System.out.println("" + o);
}
I'm trying to optimise the code below , would it be possible to directly ScreenCap to Byte Array so I can skip the step of saving it into memory.
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/colorPickerTemp.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
InputStream inputStream = new FileInputStream("/sdcard/colorPickerTemp.png");//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[1000000];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
final String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
Screencap usage:
"usage: %s [-hp] [-d display-id] [FILENAME]\n"
" -h: this message\n"
" -p: save the file as a png.\n"
" -d: specify the display id to capture, default %d.\n"
"If FILENAME ends with .png it will be saved as a png.\n"
"If FILENAME is not given, the results will be printed to stdout.\n"
So you can do something like this:
public String getScreenshotBase64() throws IOException {
return Base64.encodeToString(getScreenshotImageBytes(), Base64.NO_WRAP);
}
public byte[] getScreenshotImageBytes() throws IOException {
Process process = Runtime.getRuntime().exec("su");
OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream());
outputStream.write("/system/bin/screencap -p\n");
outputStream.flush();
byte[] bytes = readBytes(process.getInputStream());
outputStream.write("exit\n");
outputStream.flush();
outputStream.close();
return bytes;
}
public byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
I need to download mp3 files, encrypt, when necessary, to decrypt a temporary mp3 and listen.
Used as reference this answer already done in StackOverflow
Encrypting files with AES on Android
All steps works. But when I send the generated mp3 file for the MediaPlayer does not recognize and break.
These are my download and encryption method
public void executeAsyncDownload(String urlFile, String id, int position, HandlerCallback callback) {
String encryptedName = Cypher.md5(id);
if (MediaUtils.containsFile(encryptedName)) {
callback.onDownloadFinish(position);
return;
}
File dir = MediaUtils.getDestinationFolder(destination);
if (!dir.exists()) {
dir.mkdir();
}
try {
if (canceled)
return;
callback.onDownloadStart(position);
URL url = new URL(urlFile);
URLConnection connection = url.openConnection();
connection.connect();
int tamFile = connection.getContentLength();
String filePath = MediaUtils.getFilePath(MediaUtils.tempPath + encryptedName).toString();
InputStream fis = new BufferedInputStream(url.openStream());
OutputStream fos = new FileOutputStream(filePath);
File file = new File(filePath);
byte data[] = new byte[80192];
int count;
long total = 0;
while ((count = fis.read(data)) != -1) {
total += count;
if (tamFile > 0) {
int percentage = (int) (total * 100 / tamFile);
if (percentage % 20 == 0)
callback.onDownloadProgress(percentage, position);
}
fos.write(data, 0, count);
if (canceled) {
MediaUtils.deleteFile(file);
return;
}
}
if (canceled)
return;
byte[] key = (salt + cryptPassword).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 8);
SecretKeySpec sks = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8192];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
OutputStream outputEncrypted = new FileOutputStream(dir + File.separator + encryptedName);
outputEncrypted.write(d);
outputEncrypted.close();
fos.flush();
fos.close();
fis.close();
MediaUtils.deleteFile(file);//delete temp file
callback.onDownloadFinish(position);
} catch (Exception e) {
e.printStackTrace();
callback.onDownloadError(position);
}
}
This are my decryption method
#SafeVarargs
#Override
protected final File doInBackground(HashMap<String, Object>... params) {
String path = (String) params[0].get(FILE_PATH);
String fileName = String.valueOf(params[0].get(FILE_NAME));
boolean encrypted = (boolean) params[0].get(ENCRYPTED);
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + path + File.separator);
File file;
if (!encrypted) {
file = new File(dir + File.separator + fileName);
return file;
}
file = new File(dir + File.separator + Cypher.md5(fileName));
File tempMp3 = null;
try {
tempMp3 = File.createTempFile(TEMP, MP3, context.getCacheDir());
tempMp3.deleteOnExit();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream(file);
byte[] key = (DownloadManager.salt + DownloadManager.cryptPassword).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 8);
SecretKeySpec sks = new SecretKeySpec(key, "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, sks);
CipherInputStream cis = new CipherInputStream(fis, cipher);
FileOutputStream fos = new FileOutputStream(tempMp3);
int b;
byte[] d = new byte[80192];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
fos.flush();
fos.close();
cis.close();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return tempMp3;
}
You seem to have a typo in either your encrypt or decrypt method.
In encryption:
int b;
byte[] d = new byte[8192];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
In decryption:
int b;
byte[] d = new byte[80192];
while ((b = cis.read(d)) != -1) {
fos.write(d, 0, b);
}
The byte array d in decryption is about 10x larger than the byte array in encryption.
After doing this:
CipherOutputStream cos = new CipherOutputStream(fos, cipher);
int b;
byte[] d = new byte[8192];
while ((b = fis.read(d)) != -1) {
cos.write(d, 0, b);
}
OutputStream outputEncrypted = new FileOutputStream(dir + File.separator + encryptedName);
outputEncrypted.write(d);
outputEncrypted.close();
the outputEncrypted file will just contain the last buffer full of data. Furthermore, this data will not be encrypted.
First of all, if not using function decode_path , I can play .wav file with my code , and it works fine I use Jlayer and audio track to play the song.
Second, if I use function decode_path it can decode mp3 to pcm file , and pass the byte[] to function PlayAudioTrack, and let it play.
The quesion is,I don't know where my code is wrong , I use 320Kbps, 44.1Khz stereo type, Layer3 mp3, but the AudioTrack plays noise but no music~!!!!
can anyone ?
???
My code
public void PlayAudioTrack(String filePath) throws IOException{
int intSize = android.media.AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);
//Reading the file..
int count = 512 * 1024; // 512 kb
// byte[] byteData = null;
// byteData = new byte[(int)count];
//we can decode correct byte data here
byte[] byteData = null;
byteData = decode_path(filePath, 0, 20000);
File file = null;
file = new File(filePath);
FileInputStream in = null;
try {
in = new FileInputStream( file );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
int bytesread = 0, ret = 0;
int size = (int) file.length();
at.play();
while (bytesread < size) {
Log.e("devon","write byte array with sizes");
ret = in.read( byteData,0, count);
if (ret != -1) {
Log.e("devon","Write the byte array to the track");
at.write(byteData,0, ret);
bytesread += ret;
}else break;
}
at.stop();
at.release();
}
public static byte[] decode_path(String path, int startMs, int maxMs)
throws IOException{
ByteArrayOutputStream outStream = new ByteArrayOutputStream(1024);
float totalMs = 0;
boolean seeking = true;
File file = new File(path);
InputStream inputStream = new BufferedInputStream(new FileInputStream(file), 8 * 1024);
try {
Bitstream bitstream = new Bitstream(inputStream);
Decoder decoder = new Decoder();
boolean done = false;
while (! done) {
Header frameHeader = bitstream.readFrame();
if (frameHeader == null) {
done = true;
} else {
totalMs += frameHeader.ms_per_frame();
if (totalMs >= startMs) {
seeking = false;
}
if (! seeking) {
SampleBuffer output = (SampleBuffer) decoder.decodeFrame(frameHeader, bitstream);
if (output.getSampleFrequency() != 44100
|| output.getChannelCount() != 2) {
throw new IllegalArgumentException("mono or non-44100 MP3 not supported");
}
short[] pcm = output.getBuffer();
for (short s : pcm) {
outStream.write(s & 0xff);
outStream.write((s >> 8 ) & 0xff);
}
}
if (totalMs >= (startMs + maxMs)) {
done = true;
}
}
bitstream.closeFrame();
}
return outStream.toByteArray();
} catch (BitstreamException e) {
throw new IOException("Bitstream error: " + e);
} catch (DecoderException e) {
Log.w(TAG, "Decoder error", e);
throw new IOException("Decoder error: " + e);
}
}
public void PlayAudioTrack(String filePath) throws IOException{
int intSize = android.media.AudioTrack.getMinBufferSize(44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 44100, AudioFormat.CHANNEL_CONFIGURATION_STEREO,
AudioFormat.ENCODING_PCM_16BIT, intSize, AudioTrack.MODE_STREAM);
//Reading the file..
int count = 512 * 1024; // 512 kb
// byte[] byteData = null;
// byteData = new byte[(int)count];
//we can decode correct byte data here
byte[] byteData = null;
byteData = decode_path(filePath, 0, 20000);
int temp =0;
at.play();
while (temp<byteData.length)
{
at.write(byteData, temp, count);
temp+= count;
}
at.stop();
at.release();
}
I was trying to save a image from a link in a website I have written this code but this does not work ..plz help me to do this
public void imageshow(String linkText) {
try {
URL url = new URL(linkText);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[4 * 1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream("C://chart.gif");
fos.write(response);
fos.close();
} catch (Exception e) {
}
}
Taken from here
import java.net.*;
import java.io.*;
public class DownloadFile
{
public static void main(String[] args)
{
try
{
/*
* Get a connection to the URL and start up
* a buffered reader.
*/
long startTime = System.currentTimeMillis();
System.out.println("Connecting to Mura site...\n");
URL url = new URL("http://www.getmura.com/currentversion/");
url.openConnection();
InputStream reader = url.openStream();
/*
* Setup a buffered file writer to write
* out what we read from the website.
*/
FileOutputStream writer = new FileOutputStream("C:/mura-newest.zip");
byte[] buffer = new byte[153600];
int totalBytesRead = 0;
int bytesRead = 0;
System.out.println("Reading ZIP file 150KB blocks at a time.\n");
while ((bytesRead = reader.read(buffer)) > 0)
{
writer.write(buffer, 0, bytesRead);
buffer = new byte[153600];
totalBytesRead += bytesRead;
}
long endTime = System.currentTimeMillis();
System.out.println("Done. " + (new Integer(totalBytesRead).toString()) + " bytes read (" + (new Long(endTime - startTime).toString()) + " millseconds).\n");
writer.close();
reader.close();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}