i am loading image and title for list view from webservices text is f9 but image is too big.how to resize it and i want to set text in right side and image in left side in each row of list view .i am using this method Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true); but nothing appearing on emulator This is my costant class where i am loading image
public static Bitmap loadPhotoBitmap(URL url) {
Bitmap bitmap = null ;
InputStream in = null;
BufferedOutputStream out = null;
BufferedOutputStream bfs = null;
try {
FileOutputStream fos = new FileOutputStream("/sdcard/photo-tmp.jpg");
bfs = new BufferedOutputStream(fos);
in = new BufferedInputStream(url.openStream(),8192);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 8192);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bfs.write(data, 0, data.length);
bfs.flush();
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
//System.out.println(resized);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70,70, true);
return resized;
} catch (IOException e) {
// android.util.Log.e("message", "Could not load photo: " + this, e);
System.out.println("Exception while loading image");
} finally {
closeStream(in);
closeStream(out);
closeStream(bfs);
}
System.out.println("returning");
return bitmap;
}
LazyAdapter.class
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("Exception before..");
String strUrl = Constants.vctrImagePath.elementAt(counter).toString();// getting imgurl
System.out.println("Urls...." + strUrl);
URL url =null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = Constants.loadPhotoBitmap(url);
//Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
RelativeLayout layout = new RelativeLayout(mContext);
RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
TextView text1 = new TextView(mContext);
text1.setText(Constants.vctrCategory.elementAt(counter).toString());
LayoutParams params1 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
text1.setLayoutParams(params1);
text1.setTextSize(20);
text1.setGravity(Gravity.RIGHT);
layout.addView(text1);
ImageView img = new ImageView(mContext);
img.setImageBitmap(bitmap);
layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
layout.addView(img);
counter++;
return layout;
}
private void setContentView(ImageView image) {
// TODO Auto-generated method stub
}
Instead of
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
Replace that with
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
problem was not in my this bitmapfactory class.i hav resolved my isssue.
i just change code in my lazy adapter class.
Bitmap bitmap = Constants.DownloadImage(strUrl);
Bitmap resized=null;
if(bitmap!=null){
resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
}else{
System.out.println(strUrl+ "no image here");
}
before i was resizing image in my list view.while it will resize in adpter class of list view.
Related
I have long scrollview almost 50+ fields.
I'm converting that scrollview to pdf view. pdf also creating all done.
But pdf file showing data is blur (too blur).
With some merging, I provided some reference image (I mean output image).
output image
My code:
private void takeScreenShot() {
try {
//here getScroll is my scrollview id
View u = ((Activity) mContext).findViewById(R.id.getScroll);
ScrollView z = (ScrollView) ((Activity) mContext).findViewById(R.id.getScroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Bitmap bitmap = getBitmapFromView(u,totalHeight,totalWidth);
Image image;
//Save bitmap
String path = Environment.getExternalStorageDirectory()+"/Folder/";
String fileName = "report1.pdf";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.v("PDFCreator", "PDF Path: " + path);
File myPath = new File(path, fileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(0, 0);
Document document = new Document(image);
PdfWriter.getInstance(document, new FileOutputStream(myPath));
document.open();
document.add(image);
document.close();
} catch (Exception i1) {
i1.printStackTrace();
}
}
Any help?
Try this code:
View u = ((Activity) mContext).findViewById(R.id.getScroll);
u.setDrawingCacheEnabled(true);
u.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(u.getDrawingCache());
bitmap.setHasAlpha(true); //important for PNG
---------------DO SAVE WORK-----------------
v1.setDrawingCacheEnabled(false);
And at
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
change 10 to 90 or 100. it is Image Quality.
Or just change in your code to higher quality.
Try another solution:
ScrollView v= (ScrollView)findViewById(R.id.getScroll);
int height = v.getChildAt(0).getHeight()
int width = v.getWidth()
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Take a screen shot using this code and
ScrollView iv = (ScrollView) findViewById(R.id.scrollView);
Bitmap bitmap = Bitmap.createBitmap(
iv.getChildAt(0).getWidth(),
iv.getChildAt(0).getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.drawColor(Color.WHITE);
iv.getChildAt(0).draw(c);
// Do whatever you want with your bitmap
saveBitmap(bitmap);
and save the bitmap as a image
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}}
I might be late but anyway. Use png format instead, increase the quality to 100 and replace
View u = ((Activity) mContext).findViewById(R.id.getScroll);
with
View u = ((Activity) mContext).findViewById(R.id.yourfirstscrollviewchild);
Thatll do the trick.
This question already has answers here:
Android saving file to external storage
(13 answers)
Closed 2 years ago.
I develop app that save images to sd Card and all the pictures are upside i want to rotate them and save them in the rotate position i choose .
i know how to rotate on my code but the image is not saved permanently.
here is my code :
//Rotate the picture
public static Bitmap rotate(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, false);
}
//Resize image
public void resizeImage(String path , int Wdist,int Hdist){
try
{
int inWidth = 0;
int inHeight = 0;
InputStream in = new FileInputStream(path);
// decode image size (decode metadata only, not the whole image)
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
in.close();
in = null;
// save width and height
inWidth = options.outWidth;
inHeight = options.outHeight;
// decode full image pre-resized
in = new FileInputStream(path);
options = new BitmapFactory.Options();
// calc rought re-size (this is no exact resize)
options.inSampleSize = Math.max(inWidth/Wdist, inHeight/Hdist);
// decode full image
Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
// calc exact destination size
Matrix m = new Matrix();
RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
RectF outRect = new RectF(0, 0, Wdist, Hdist);
m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
float[] values = new float[9];
m.getValues(values);
// resize bitmap
Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
// save image
try
{
FileOutputStream out = new FileOutputStream(path);
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
}
catch (Exception e)
{
Log.e("Image", e.getMessage(), e);
}
}
catch (IOException e)
{
Log.e("Image", e.getMessage(), e);
}
}
thanks for the helpers :)
You'll need to save the Bitmap back.
try {
File dir = new File("path/to/directory");
if(!dir.exists())
dir.mkdirs();
File file = new File(dir, "original_img_name.png");
FileOutputStream out;
out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
out.close();
} catch(Throwable ignore) {}
}
Edit 1 :
Replace
bmp.compress(Bitmap.CompressFormat.PNG, 90, out); with
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out); and set correct values for the directory path and the image name. If you want to replace the previous images, use the original path and image name.
Also, make sure you include the following permission.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
You can also try this one
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),source.getHeight(), matrix, true);
Go through this link
how to rotate a bitmap 90 degrees
The following code can help you compress and resize the bitmap.
Note:
Create a String type variable with name of photoPath and store the photo url in it.
public void compressImage(){
Log.i("compressPhoto", "Compress and resize photo started.");
// Getting Image
InputStream in = null;
try {
in = new FileInputStream(photoPath);
} catch (FileNotFoundException e) {
Log.e("TAG","originalFilePath is not valid", e);
}
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap = bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.2), (int)(bitmap.getHeight()*0.2), true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, stream);
byte[] byteArray = stream.toByteArray();
// Storing Back
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(photoPath);
outStream.write(byteArray);
outStream.close();
} catch (Exception e) {
Log.e("TAG","could not save", e);
}
}
I'm developing an app that combines two bitmaps, where one bitmap is from drawable, and the other is taken from a camera snapshot. However the pictures always end up incomplete. Half the picture is fine, but the other half is gray. Is there a way to make sure that the file is completed before the app moves on with the code? Below is the code that works with writing and saving the file. Thanks
Combine.java
protected void createPostcard(byte[] data, File pictureFile, CameraActivity app, Button shareButton,
Button newButton) {
try {
Bitmap photo = BitmapFactory.decodeByteArray(data, 0, data.length);
Bitmap splash = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(app.getResources(),
R.drawable.wishsplash), photo.getWidth(), photo.getHeight(), false);
Bitmap postcard = Bitmap.createBitmap(photo.getWidth(), photo.getHeight(), photo.getConfig());
Canvas canvas = new Canvas(postcard);
canvas.drawBitmap(photo, new Matrix(), null);
canvas.drawBitmap(splash, 0, 0, null);
savePostcard(postcard, pictureFile, app, shareButton, newButton);
} catch (Exception e) {
}//end catch
}//end createPostcard
/**
* Saves the postcard
*/
private void savePostcard(Bitmap postcard, File pictureFile, CameraActivity app, Button shareButton,
Button newButton) {
BitmapDrawable mBitmapDrawable = new BitmapDrawable(postcard);
Bitmap mNewSaving = mBitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
mNewSaving.compress(CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
save(byteArray, pictureFile, app);
shareButton.setBackgroundResource(R.drawable.sharebutton);
newButton.setBackgroundResource(R.drawable.newbutton);
shareButton.setEnabled(true);
newButton.setEnabled(true);
}//end savePostcard
/**
* Check if external is available. If not, postcard will be saved in internal.
* #retun
*/
private void save(byte[] data, File pictureFile, CameraActivity app) {
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
FileOutputStream fos = new FileOutputStream(pictureFile);
imageUri = Uri.fromFile(pictureFile);
fos.write(data);
imageFile = pictureFile;
fos.close();
app.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
} else {
File cache = app.getCacheDir();
File internalPic = new File(cache, pictureFile.getName());
FileOutputStream fos = new FileOutputStream(internalPic);
imageUri = Uri.fromFile(internalPic);
imageFile = internalPic;
fos.write(data);
fos.close();
}//end else
} catch (FileNotFoundException e) {
System.out.println("FILENOTFOUND");
} catch (IOException e) {
System.out.println("IOEXCEPTION");
}//end catch
}//end getStorage
try this code
public Bitmap PutoverBmp(Bitmap all, Bitmap scaledBorder) {
Paint paint = new Paint();
final int width = bmp.getWidth(); // bmp is your main Bitmap
final int height = bmp.getHeight();
patt = Bitmap.createScaledBitmap(bmp, width, height, true);
Bitmap mutableBitmap = patt.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
scaledBorder = Bitmap.createScaledBitmap(border, width, height, true);
paint.setAlpha(100);
canvas.drawBitmap(scaledBorder, 0, 0, paint);
return mutableBitmap;
}
simply call this Bitmap combine = (bmp , yourOtherBitmap);
I download and resize my bitmap using the following code :
private void downloadImage(String urlImg, ImageView v) {
Bitmap bitmap = null, resized= null;
try {
URL urlImage = new URL("http://.../" + urlImg);
HttpURLConnection connexion = (HttpURLConnection) urlImage
.openConnection();
InputStream inputStream = connexion.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
resized = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
v.setImageBitmap(resized);
connexion.disconnect();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
and in my onCreate() function, I create dynamically ImageViews where i use my previous function
ImageView view = new ImageView(this);
downloadImage(list.getOneAnnonce(i).getPhoto(), view);
trMain.addView(view);
if I dont try to resize bitmap, there is no error but if i try to resize -> Force close
I use such code for downloading image from URL:
public static Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
When I send URL "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png" it works fine, but when I use "http://www.hospimedica.com/images/stories/articles/article_images/_CC/20110328%20-%20DJB146.gif" it returns me null.
What's wrong with this URL?
Why are you writing your own method to downlaod an image ? Android has inbuilt method to achieve this.. Just use
URL url = new URL("Your url");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());