How to Save a PictureDrawable as a JPEG/PNG file in Android - java

I have PictureDrawable that I wish to save as an image (JPEG/PNG) but I can't seem to find any information how to go about this.
I tried this but it does not seem to work
PictureDrawable myDrawable = GetPictureDrawable();
Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
myDrawable.draw(new Canvas(bitmap));
bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream("/MyLocation/MyImage.jpg"));
What am I doing wrongly?

//Convert PictureDrawable to Bitmap
private static Bitmap pictureDrawable2Bitmap(PictureDrawable pictureDrawable){
Bitmap bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
return bitmap;
}

Related

how to set Custom font for Widget?

i want to set custom font for TextView in widget,How?
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weather_widget);
views.setTextViewText(R.id.txv_widget_location, "my text");
Just replace xyz.ttf with your chosen font.
public Bitmap createBitmap(String texttoshow)
{
Bitmap myBitmap = Bitmap.createBitmap(160, 84, Bitmap.Config.ARGB_8888);
Canvas myCanvas = new Canvas(myBitmap);
Paint paint = new Paint();
Typeface weatherwidget = Typeface.createFromAsset(this.getAssets(),"xyz.ttf");
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(weatherwidget);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(65);
paint.setTextAlign(Align.CENTER);
myCanvas.drawText(texttoshow, 80, 60, paint);
return myBitmap;
}
The above code applies the font and text to image view.
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.weather_widget);
views.setImageViewBitmap(R.id.txv_widget_location, createBitmap("my_text"));

Android LibVLC getBitmap from a TextureView

I am trying to retrieve a frame from a video that is playing back using LibVLC in android. For reference, this is how I am starting LibVLC. ffmpegSv is a TextureView
public void startMediaPlayer() {
ArrayList<String> options = new ArrayList<>();
options.add("--no-drop-late-frames");
options.add("--no-skip-frames");
options.add("-vvv");
options.add("--no-osd");
options.add("--rtsp-tcp");
options.add("--no-snapshot-preview");
options.add("--no-video-title");
options.add("--no-spu");
videoVlc = new LibVLC(getActivity(), options);
TextureView surfaceView = (TextureView) getActivity().findViewById(R.id.streamView);
newVideoMediaPlayer = new org.videolan.libvlc.MediaPlayer(videoVlc);
final IVLCVout vOut = newVideoMediaPlayer.getVLCVout();
vOut.setVideoSurface(ffmpegSv.getSurfaceTexture());
vOut.setWindowSize(ffmpegSv.getWidth(), ffmpegSv.getHeight());
vOut.attachViews();
Media videoMedia = new Media (videoVlc, Uri.parse("rtsp://1.1.1.1/abc.mov"));
newVideoMediaPlayer.setMedia(videoMedia);
newVideoMediaPlayer.play();
}
And this is how I am attempting to get the bitmap from it. I should note this method worked correctly when using the android MediaPlayer.
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
if (mStream != null) {
if (idx++ % 10 == 0) {
(new Runnable() {
#Override
public void run() {
FileOutputStream out = null;
Bitmap b = ffmpegSv.getBitmap(ffmpegSv.getWidth(), ffmpegSv.getHeight());
Bitmap bm = Bitmap.createScaledBitmap(b2, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
byte[] arr = bos.toByteArray();
mStream.onJpegFrame(arr, 0L);
b.recycle();
bm.recycle();
}
}).run();
idx = 0;
}
}
}
However, the image that is being produced has a sliver of the original image from the TextureView around the edge almost like a border, but the rest of the image is obscured by a black box.
The only thing I can think of is that VLC uses some sort of overlay for subtitles etc that when pulled out with getBitmap() is losing its transparency. However, I am not 100% sure this is the case. Is there a way to check if this is the case, or disable any sort of overlays that VLC could be adding?
EDIT : I have added a sample image to demonstrate the problem:
You can just make out the bottom, right and top of the background image and a clear rectangle over the top of it.
Bitmap b = ffmpegSv.getBitmap(ffmpegSv.getWidth(), ffmpegSv.getHeight());
Bitmap bm = Bitmap.createScaledBitmap(b2, 640, 480, true);
Aren't you scaling something else here?
What is b2?

how to draw text on image view android

I have an app that calculate time of phone usage and you can share it on social networks, instead of normal gettext() I want to put the results on an image and save it to phone. How can I create an image that I can save to the phone that includes custom text?
What you want to do is to paint to a Canvas that's linked to a Bitmap, and save the bitmap. Here's a few bits of code that you should be able to string together to make it work. Note that you'll have to still add the paining to the canvas, in the getBitmap() function.
private Bitmap getBitmap() {
Bitmap bitmap = Bitmap.createBitmap(mPieToss.getWidth(),
mPieToss.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
// Draw things to your canvas. They will be included as your BitMap, which is saved later on
return bitmap;
}
public void save() {
Bitmap bitmap = getBitmap();
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String filename = "Imagen_" + timestamp + ".jpg";
File file = new File(path, filename);
FileOutputStream stream;
// This can fail if the external storage is mounted via USB
try {
stream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, stream);
stream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mUri = Uri.fromFile(file);
bitmap.recycle();
}
First of all convert your layout to bitmap:
View contentLayout; // your layout with bavkground image and TextView
Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
content.draw(canvas);
Now you can save it to the file:
FileOutputStream fos = new FileOutputStream(fileName, false);
bitmap.compress(Bitmap.CompressFormat.PNG, 75, fos);
fos.flush();
fos.close();

Saving canvas to bitmap on Android

I'm having some difficulty with regards to placing the contents of a Canvas into a Bitmap. When I attempt to do this, the file gets written with a file size of around 5.80KB but it appears to be completely empty (every pixel is '#000').
The canvas draws a series of interconnected lines that are formed by handwriting. Below is my onDraw for the View. (I'm aware that it's blocking the UI thread / bad practices/ etc.., however I just need to get it working)
Thank you.
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (IsTouchDown) {
// Calculate the points
Path currentPath = new Path();
boolean IsFirst = true;
for(Point point : currentPoints){
if(IsFirst){
IsFirst = false;
currentPath.moveTo(point.x, point.y);
} else {
currentPath.lineTo(point.x, point.y);
}
}
// Draw the path of points
canvas.drawPath(currentPath, pen);
// Attempt to make the bitmap and write it to a file.
Bitmap toDisk = null;
try {
// TODO: Get the size of the canvas, replace the 640, 480
toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
canvas.setBitmap(toDisk);
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));
} catch (Exception ex) {
}
} else {
// Clear the points
currentPoints.clear();
}
}
I had similar problem and i've got solution. Here full code of a task /don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission in manifest/
public Bitmap saveSignature(){
Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
this.draw(canvas);
File file = new File(Environment.getExternalStorageDirectory() + "/sign.png");
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
first create a blank bitmap , then create a canvas with that blank bitmap
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bitmap_object = Bitmap.createBitmap(width, height, conf);
Canvas canvas = new Canvas(bitmap_object);
now draw your lines on canvas
Path currentPath = new Path();
boolean IsFirst = true;
for(Point point : currentPoints){
if(IsFirst){
IsFirst = false;
currentPath.moveTo(point.x, point.y);
} else {
currentPath.lineTo(point.x, point.y);
}
}
// Draw the path of points
canvas.drawPath(currentPath, pen);
Now access your bitmap via bitmap_object
You'll have to draw after setting the bitmap to the canvas. Also use a new Canvas object like this:
Canvas canvas = new Canvas(toDisk);
canvas.drawPath(currentPath, pen);
toDisk.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File("arun.png")));
I recommend using PNG for saving images of paths.
you must call canvas.setBitmap(bitmap); before drawing anything on Canvas. After calling canvas.setBitmap(bitmap); draw on Canvas and then save the Bitmap you passed to Canvas.
May be
canvas.setBitmap(toDisk);
is not in correct place.
Try this :
toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));
canvas.setBitmap(toDisk);

Make an Image as a backgound in java android for edit

I had created an image by the following code:
Bitmap bmp = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
try {
int tile1ResID = getResources().getIdentifier("drawable/m" + String.valueOf(tileOfPoint.x) + "_" + String.valueOf(tileOfPoint.y), "drawable", "com.example.sabtt1");
canvas.drawBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), tile1ResID), 256, 256, true), 0, 0, null);
canvas.save();
}
catch (Exception e) {
}
canvas.save();
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
now I want to make it as background. So that the user can add an image or draw on it.
How can I set it as background?
Is it possible to add the image and draw by finger at the same time?
I use this code for draw:
#Override
public void onClick(View arg0) {
try {
Bitmap gestureImg = gesture.getGesture().toBitmap(100, 100, 8, Color.BLACK);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
gestureImg.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] bArray = bos.toByteArray();
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putExtra("draw", bArray);
startActivity(intent);
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(Activity1.this, "No draw on the string", 3000).show();
}
}
and OnDragListener for add and move images.
I know that I should use the folowing code for background:
LinearLayout ll = new LinearLayout(this);
ll.setBackgroundResource(R.drawable.nn);
this.setContentView(ll);
but by using this code, I can't see other images.
Thanks in advance.
You can just draw on the main bitmap the other bitmaps:
Bitmap bmp = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
bmp = <load from resource>
Canvas canvas = new Canvas(bmp);
Bitmap gestureImg = <get bitmap from gesture or loading>
canvas.drawBitmap(gestureImg);
then load the final bitmap:
ImageView imgMap1 = (ImageView) findViewById(R.id.imgMap1);
imgMap1.setImageDrawable(new BitmapDrawable(Bitmap.createBitmap(bmp, 0, 0, 500, 500)));
Or you can store the main bitmap and all other gesture/loaded bitmaps in separate objects and when you want to update the imgMap1 you make your combined bitmap;
Also to use as background the new bitmap use:
ll.setBackgroundDrawable( new BitmapDrawable( bmp ) );

Categories