creating .bmp image file from Bitmap class - java

I've created an application that uses sockets in which the client receives the image and stores the data of the image in Bitmap class....
Can anyone please tell me how to create a file named myimage.png or myimage.bmp from this Bitmap object
String base64Code = dataInputStream.readUTF();
byte[] decodedString = null;
decodedString = Base64.decode(base64Code);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);

Try following code to save image as PNG format
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
Here, 100 is quality to save in Compression. You can pass anything between 0 to 100. Lower the digit, poor quality with decreased size.
Note
You need to take permission in Android Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit
To save your image to .BMP format, Android Bitmap Util will help you. It has very simple implementation.
String sdcardBmpPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sample_text.bmp";
Bitmap testBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_text);
AndroidBmpUtil bmpUtil = new AndroidBmpUtil();
boolean isSaveResult = bmpUtil.save(testBitmap, sdcardBmpPath);

try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}

Related

How to save BufferedImage to FastDFS in Java?

I have an image and I do somethings with it, finally I get an BufferedImage object(the sub image of original image), now I want to save the sub image to FastDFS without save it in my local, what should I do?
I have already save sub image as file to my local, but I don't want to do like this, because it makes waste.
String oriPicPathInFastDFS = "http://127.0.0.1/xx/xx/xx/xx";
BufferedImage image = null;
try {
image = ImageIO.read(new URL(oriPicPathInFastDFS));
} catch (IOException e) {
e.printStackTrace();
}
// do something
// this is the sub image that I want to save to FastDFS
BufferedImage subImage = image.getSubimage(5, 5, 5, 5);
// these code can save the sub image to my local and then upload to fastDFS
String localPath = "/home/xx/x/xx.jpg";
File detectionFile = new File(localPath);
try {
detectionFile.createNewFile();
ImageIO.write(subImage, "jpg", detectionFile);
} catch (IOException e) {
e.printStackTrace();
}
// upload to fast dfs
I want to upload the subImage to fastDFS without save it to my local.
Fine, I got a method to solve this question.
// change the BufferedImage to byte[]
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
boolean flag = ImageIO.write(sunImage, "jpg", out);
} catch (IOException e) {
e.printStackTrace();
}
byte[] byteArray = out.toByteArray();
// then save the byteArray to fast DFS

Android Studio - Convert Bitmap into java.io.File

I have created a video thumbnail from a video file. What I need to do is to create a java.io.File from the Bitmap in order to upload the thumbnail to a server. How could achieve this?
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoFile.getPath(), MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
File thumbFile = ?
can use the following code:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
//f.createNewFile(); (No need to call as FileOutputStream will automatically create the file)
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
you can also try this method: it does not convert bitmap to byte Array..
private static void bitmap_to_file(Bitmap bitmap, String name) {
File filesDir = getAppContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
}

Extract Thumbnail for specific second from MP4 file in Android

I have a list of mp4 files that i need to extract a thumbnail for each one.
Thumbnail criteria:
The thumbnail must be in Base64 format
The thumbnail has a specific size which will be provided as a method parameter
It must be extracted from the frame in the middle of the file (e.g. if the video duration is 10s then the thumbnail must be from the frame in 5th second.
1 and 2 are currently achieved but I'm not sure how to do 3.
This is my code:
public static String getVideoDrawable(String path, int height, int width) throws OutOfMemoryError{
try {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path, android.provider.MediaStore.Images.Thumbnails.MINI_KIND);
bitmap = Bitmap.createScaledBitmap(bitmap, height, width, false);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
You need to use the MediaMetadataRetriever for that.
MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
try {
metadataRetriever.setDataSource(path);
String duration=metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long time=Long.valueOf(duration)/2;
Bitmap bitmap = metadataRetriever.getFrameAtTime(time,MediaMetadataRetriever.OPTION_NEXT_SYNC);
//now convert to base64
} catch (Exception ex) {
}
http://developer.android.com/intl/es/reference/android/media/MediaMetadataRetriever.html#getFrameAtTime%28long,%20int%29

Liferay DLFileEntry image conversion is not fully converting the image

I am converting an image as a DLFileEntry from JPG to PNG format using the following code.
try {
DLFileEntry dlFileEntry = DLFileEntryServiceUtil.getFileEntry(dlFileEntryId);
InputStream inputStream = dlFileEntry.getContentStream();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
byte[] byteArray = buffer.toByteArray();
ImageBag imageBag = ImageToolUtil.read(byteArray);
RenderedImage renderedImage = imageBag.getRenderedImage();
if (renderedImage == null) {
throw new IOException("Unable to decode image");
}
renderedImage = ImageToolUtil.scale(renderedImage, 2000);
buffer = new ByteArrayOutputStream();
ImageIO.write(renderedImage, "png", buffer);
InputStream fis = new ByteArrayInputStream(buffer.toByteArray());
DLAppServiceUtil.updateFileEntry(
dlFileEntry.getFileEntryId(),
dlFileEntry.getName(),
MediaType.IMAGE_PNG_VALUE,
dlFileEntry.getTitle(),
dlFileEntry.getDescription(),
"",
true,
fis,
buffer.size(),
serviceContext);
} catch (Exception e) {
e.printStackTrace();
}
Even though it updates the image content type and extension in "Documents and Media", when we try downloading the image, it is still in JPG format.
The image looks like above in Documents and Media. You can see that the content type has become image/png.
Above shows the screenshot while I tried to Download this image and save it. It is still in the original format of JPG when I try downloading. What should I do in addition to the code above, inorder to completely convert the image to PNG?
You still store the old file name: dlFileEntry.getName()
I would guess that jpeg or jpg is the extension of the old file name and the browser determines his file filter from the extension.
So better exchange the extension as well:
DLAppServiceUtil.updateFileEntry(
dlFileEntry.getFileEntryId(),
dlFileEntry.getName().replaceAll("\\..*?$",".png"),
...
This will change the extension that is stored for that file

how to get a image for a label from FileOutPutStream in java?

i created a QR generator in java.I tested my application using FileOutPutStream.So it worked properly,now i need to get the generated QR image to a jLabel before save,so how to do this.please help me??
this is my code:
ByteArrayOutputStream out = QRCode.from("Hello World").to(ImageType.PNG).stream();
ByteArrayOutputStream webout = QRCode.from("http://viralpatel.net").to(ImageType.PNG).stream();
try {
FileOutputStream fout = new FileOutputStream(new File("D:\\QR_Code.JPG"));
BufferedImage image= ImageIO.read(new FileOutputStream(fout)));
fout.write(out.toByteArray());
fout.flush();
fout.close();
} catch (Exception e){
}
A ByteArrayOutputStream is used to write to a final byte array.
A ByteArrayInputStream allows to read from an initial byte array.
So:
ByteArrayOutputStream out = ...
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
BufferedImage image= ImageIO.read(in);

Categories