Kotlin bitmap to string

Kotlin java convert a bytebuffer to string

e.g. the to can placed after the to improve alignment and packing of the object, or padding can be added between fields. That gives you similar methods for reading primitive data from arbitrary offsets.

How can I convert Bitmap to String, String to bitmap in kotlin

fun BitMapToString(bitmap: Bitmap): String

That is all. You just have to decode the base 64 string first into a byte array.:

val imageBytes = Base64.decode(string, 0) val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) 

I tried the code that showed as wrong and it worked that way

 @SuppressLint("NewApi") @TargetApi(Build.VERSION_CODES.O) @RequiresApi(Build.VERSION_CODES.O) fun BitMapToString(bitmap: Bitmap): String

Java — Problems converting byte array to string and back, String.getBytes («UTF-16») adds a byte-order-marker character to the output to identify the order of the bytes. You should use UTF-16LE or UTF-16BE …

How to correctly read Flux<DataBuffer> and convert it to a single inputStream

This is really not as complicated as other answers imply.

The only way to stream the data without buffering it all in memory is to use a pipe, as @jin-kwon suggested. However, it can be done very simply by using Spring’s BodyExtractors and DataBufferUtils utility classes.

private InputStream readAsInputStream(String url) throws IOException < PipedOutputStream osPipe = new PipedOutputStream(); PipedInputStream isPipe = new PipedInputStream(osPipe); ClientResponse response = webClient.get().uri(url) .accept(MediaType.APPLICATION.XML) .exchange() .block(); final int statusCode = response.rawStatusCode(); // check HTTP status code, can throw exception if needed // . Fluxbody = response.body(BodyExtractors.toDataBuffers()) .doOnError(t -> < log.error("Error reading body.", t); // close pipe to force InputStream to error, // otherwise the returned InputStream will hang forever if an error occurs try(isPipe) < //no-op >catch (IOException ioe) < log.error("Error closing streams", ioe); >>) .doFinally(s -> < try(osPipe) < //no-op >catch (IOException ioe) < log.error("Error closing streams", ioe); >>); DataBufferUtils.write(body, osPipe) .subscribe(DataBufferUtils.releaseConsumer()); return isPipe; > 

If you don’t care about checking the response code or throwing an exception for a failure status code, you can skip the block() call and intermediate ClientResponse variable by using

flatMap(r -> r.body(BodyExtractors.toDataBuffers())) 

A slightly modified version of Bk Santiago’s answer makes use of reduce() instead of collect() . Very similar, but doesn’t require an extra class:

body.reduce(new InputStream() < public int read() < return -1; >>, (s: InputStream, d: DataBuffer) -> new SequenceInputStream(s, d.asInputStream()) ).flatMap(inputStream -> /* do something with single InputStream */ 
body.reduce(object : InputStream() < override fun read() = -1 >) < s: InputStream, d ->SequenceInputStream(s, d.asInputStream()) > .flatMap < inputStream ->/* do something with single InputStream */ > 

Benefit of this approach over using collect() is simply you don’t need to have a different class to gather things up.

I created a new empty InputStream() , but if that syntax is confusing, you can also replace it with ByteArrayInputStream(«».toByteArray()) instead to create an empty ByteArrayInputStream as your initial value instead.

Here comes another variant from other answers. And it’s still not memory-friendly.

static Mono asStream(WebClient.ResponseSpec response) < return response.bodyToFlux(DataBuffer.class) .map(b ->b.asInputStream(true)) .reduce(SequenceInputStream::new); > static void doSome(WebClient.ResponseSpec response) < asStream(response) .doOnNext(stream ->< // do some with stream // close the stream. >) .block(); > 

How to Convert byte Array to String in Java, How to convert byte array to String in Java. The process of converting a byte array to a String is called decoding. This process requires a Charset. Though, we …

From ByteBuffer to object

You can do this with Unsafe. It supports copying of data directly between native memory and objects. However in Java you have no control over the order of fields, nor how much padding is used. e.g. the boolean to can placed after the int to improve alignment and packing of the object, or padding can be added between fields.

You are better off copying the field one at a time. While this might seem slower, in reality the main issue is bring the data into the L1 cache and the copy of each field is pretty quick by comparison.

The reasonably idiomatic and maintainable way to do something like this, available since Java 1.0, is with a DataInputStream.

void fillFromBytes(byte[] arr) throws IOException < DataInputStream dis = new DataInputStream(new ByteArrayInputStream(arr)); aDouble = dis.readDouble(); anotherDouble = dis.readDouble(); aBoolean = ( dis.readByte() != 0 ); . 

Since you're already working with a ByteBuffer (since 1.4), however, you have a range of methods directly on it such as getDouble(). That gives you similar methods for reading primitive data from arbitrary offsets.

void fillFromBytes(ByteBuffer buf) throws IOException < aDouble = buf.getDouble(); anotherDouble = buf.getDouble(); aBoolean = ( buf.getByte() != 0 ); . 

You can deal with padding by skipping to an absolute position after it, e.g.

 anotherDouble = buf.getDouble(0x24); 

or by skipping over it a byte at a time:

 int npad = buf.getShort(); for (int i=0 ; i < npad; i++) buf.getByte(); 

Convert String to Byte Array and Reverse in Java, First, we'll look at various ways to convert a String to a byte array. Then we'll look at similar operations in reverse. 2. Converting a String to Byte …

Convert ByteArray to ShortArray

the array() method of ShortBuffer is an optional operation and will work only when the ShortBuffer is backed by a short array ( short[] ).

public final short[] array()

Returns the short array that backs this buffer (optional operation).

Modifications to this buffer's content will cause the returned array's content to be modified, and vice versa.

Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array.

since your ShortBuffer is not backed by a short[] , because is created by a ByteBuffer , the array() method will throw UnsupportedOperationException .

you can use the hasArray() method to check whether is safe to call array() .

Java byte array to ByteBuffer or ByteBuffer to byte array, I need to show that byte array as a bytebuffer "without copying" byte aparapiData[]; ByteBuffer buffer; //here bytebuffer buffer.clear(); …

Источник

How to convert an image into base64 String in Android using Kotlin?

This example demonstrates how to convert an image into a Base64 string on Android using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

Step 3 − Add the following code to src/MainActivity.kt

import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.util.Base64 import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import java.io.ByteArrayOutputStream class MainActivity : AppCompatActivity() < lateinit var textView: TextView override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" textView = findViewById(R.id.textView) val byteArrayOutputStream = ByteArrayOutputStream() val bitmap = BitmapFactory.decodeResource(resources, R.drawable.image) bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) val imageBytes: ByteArray = byteArrayOutputStream.toByteArray() val imageString: String = Base64.encodeToString(imageBytes, Base64.DEFAULT) textView.text = imageString >>

Step 4 − Add the following code to androidManifest.xml

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Источник

Android – String to Bitmap in Kotlin

I'm new to Kotlin and I can't seem to work this one out. I get a base64String and I need an image.

val imageBytes = string.toByteArray(). // string is the base64image val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) 

Problem is that when I try to access the image , I get a SkAndroidCodec::NewFromStream returned null message in the log. I wanted to use it inside a method with a return but it kept crashing on return image .

How do I convert it correctly?

I have checked and string is not empty, imageBytes has content and imageBytes.size is over 60000. The same string I use in swift and it converts image without any modifications, so I am confident the string is not the problem.

Best Solution

val imageBytes = Base64.decode(string, 0) val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) 

That is all. You just have to decode the base 64 string first into a byte array.

Android – Strange OutOfMemory issue while loading an image to a Bitmap object

To fix the OutOfMemory error, you should do something like this:

BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options); 

This inSampleSize option reduces memory consumption.

Here's a complete method. First it reads image size without decoding the content itself. Then it finds the best inSampleSize value, it should be a power of 2, and finally the image is decoded.

// Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) < try < // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // The new size we want to scale to final int REQUIRED_SIZE=70; // Find the correct scale value. It should be the power of 2. int scale = 1; while(o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) < scale *= 2; >// Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); > catch (FileNotFoundException e) <> return null; > 
Android – Save bitmap to location
try (FileOutputStream out = new FileOutputStream(filename)) < bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance // PNG is a lossless format, the compression factor (100) is ignored >catch (IOException e)

Источник

Android – String to Bitmap in Kotlin

I'm new to Kotlin and I can't seem to work this one out. I get a base64String and I need an image.

val imageBytes = string.toByteArray(). // string is the base64image val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) 

Problem is that when I try to access the image , I get a SkAndroidCodec::NewFromStream returned null message in the log. I wanted to use it inside a method with a return but it kept crashing on return image .

How do I convert it correctly?

I have checked and string is not empty, imageBytes has content and imageBytes.size is over 60000. The same string I use in swift and it converts image without any modifications, so I am confident the string is not the problem.

Best Solution

val imageBytes = Base64.decode(string, 0) val image = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) 

That is all. You just have to decode the base 64 string first into a byte array.

Android – Strange OutOfMemory issue while loading an image to a Bitmap object

To fix the OutOfMemory error, you should do something like this:

BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap preview_bitmap = BitmapFactory.decodeStream(is, null, options); 

This inSampleSize option reduces memory consumption.

Here's a complete method. First it reads image size without decoding the content itself. Then it finds the best inSampleSize value, it should be a power of 2, and finally the image is decoded.

// Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) < try < // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f), null, o); // The new size we want to scale to final int REQUIRED_SIZE=70; // Find the correct scale value. It should be the power of 2. int scale = 1; while(o.outWidth / scale / 2 >= REQUIRED_SIZE && o.outHeight / scale / 2 >= REQUIRED_SIZE) < scale *= 2; >// Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); > catch (FileNotFoundException e) <> return null; > 
Android – Save bitmap to location
try (FileOutputStream out = new FileOutputStream(filename)) < bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance // PNG is a lossless format, the compression factor (100) is ignored >catch (IOException e)

Источник

Читайте также:  Static functions in cpp file
Оцените статью