Enviar y recibir imágenes

Product deprecation notice

Effective April 30th, 2026, Vonage In-App Messaging will no longer be available. Access for new users will be closed, and the service will be discontinued for all existing users.

If you have any questions regarding this product’s discontinuation, please contact your account manager or our support team.

Visión general

Esta guía cubre el envío y recepción de imágenes dentro de una conversación.

Antes de empezar, asegúrese de que ha añadido el SDK a su aplicación y eres capaz de crear una conversación.

NOTA: Hay disponible un tutorial paso a paso para crear una aplicación de chat aquí.

Esta guía hará uso de los siguientes conceptos:

  • Eventos de conversación - message eventos que se disparan en una Conversación, después de ser Miembro

Enviar una imagen

Dada una conversación de la que ya eres miembro:

// Scenario #1: Send an image from a URL
conversation.sendMessage({
    "message_type": "image",
    "image": {
        "url": "https://example.com/image.jpg"
    }
}).then((event) => {
    console.log("message was sent", event);
}).catch((error)=>{
    console.error("error sending the message", error);
});

// Scenario #2: Upload an image from a file input to Vonage, then send
// Note: the URL will need to be downloaded using the fetch image method mentioned in the next section.
    
const fileInput = document.getElementById('fileInput');
const params = {
    quality_ratio : "90",
    medium_size_ratio: "40",
    thumbnail_size_ratio: "20"
}
conversation.uploadImage(fileInput.files[0], params).then((imageRequest) => {
    imageRequest.onreadystatechange = () => {
        if (imageRequest.readyState === 4 && imageRequest.status === 200) {
            try {
                const { original, medium, thumbnail } = JSON.parse(imageRequest.responseText);
                const message = {
                    message_type: 'image',
                    image: {
                        url: original.url ?? medium.url ?? thumbnail.url
                    }
                }
                return conversation.sendMessage(message);
            } catch (error) {
                console.error("error sending the image", error);
            }
        }
        if (imageRequest.status !== 200) {
            console.error("error uploading the image");
        }
    };
    return imageRequest;
}).catch((error) => {
    console.error("error uploading the image ", error);
});

Recibir una URL de imagen

A message se recibirá cuando un miembro envíe una imagen a una conversación:

conversation.on('message', (sender, event) => {
  if (event.body.message_type === 'image'){
    console.log('*** Image sender: ', sender);
    console.log('*** Image event: ', event);
  }
});

Descargar imágenes de Vonage

Cliente web

Para descargar una imagen es necesario utilizar la función Obtener imagen método.

Cliente móvil (Android, iOS)

Para descargar una imagen es necesario añadir JWT a la solicitud de recuperación de imagen. El JWT se pasa como una cabecera de autorización (Authorization: Bearer <JWT> ). Este es el JWT que se utilizó para iniciar la sesión del usuario.

Varias librerías de imágenes manejan las cabeceras de las peticiones de forma diferente, así que a continuación encontrarás ejemplos de las librerías más populares. Observe que el JWT se establece como Authorization de la solicitud:

// ==== LOAD IMAGE USING COIL ==== 
// https://github.com/coil-kt/coil
private fun loadImageUsingCoil(url: String, jwt: String, context: Context) {
    imageView.load(
        Uri.parse(url),
        context.imageLoader,
    ) {
        addHeader("Authorization", "bearer $jwt")
    }
}

// ==== LOAD IMAGE USING GLIDE ==== 
// https://github.com/bumptech/glide
private fun loadImageUsingGlide(url: String, jwt: String, context: Context) {
    val build = LazyHeaders.Builder()
        .addHeader("Authorization", "bearer $jwt")
        .build()

    val glideUrl = GlideUrl(url, build)

    Glide.with(context)
        .load(glideUrl)
        .into(imageView)
}

// ==== LOAD IMAGE USING PICASSO ====
// https://github.com/square/picasso

// Define custom Authentication interceptor
class AuthenticationInterceptor(private val jwt: String) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response = chain.request().let {
        val newRequest = it.newBuilder()
            .header("Authorization", "bearer $jwt")
            .build()

        chain.proceed(newRequest)
    }
}

// Create Picasso instance that uses the Authenticator
private fun getPicassoInstance(jwt: String): Picasso {
    val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(AuthenticationInterceptor(jwt))
        .build()

    return Picasso.Builder(requireContext()).downloader(OkHttp3Downloader(okHttpClient)).build()
}

// Load image using custom picasso instance (that under the hood uses the authentication interceptor)
private fun loadImageUsingPicasso(url: String, jwt: String, context: Context) {
    getPicassoInstance(jwt)
        .load(url)
        .into(imageView)
}

Referencia