」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 建立 AI 貼圖製作平台。

使用 OpenAI GPT 和 DALL·E 模型,使用 AI/ML API、Next.js、React 和 Tailwind CSS 建立 AI 貼圖製作平台。

發佈於2024-11-01
瀏覽:370

I got bored. You too? ?

Hmm... ?

What about creating an AI Sticker Maker platform? To be honest, it's a really interesting idea. And hey, we might even generate some profit by simply integrating Stripe as a payment provider. ? Yeah, why not?

So, let's get started. Or at least give it a shot! ?

Quick Introduction ?

First things first, let's sketch out some pseudocode or make a plan (unless you're a true builder who codes from the hip). It should go something like this:

  1. User enters a prompt (a text description of how the sticker should look).
  2. Our AI Sticker Maker will generate a really cutesy sticker. Ta-da! ?

Easy-peasy, isn't it? ?

But wait, let me clarify. We're going to use two models: GPT-4o and DALL·E 3, both from OpenAI. They're hyped, for real! ?

We'll be using the AI/ML API, which provides access to 200 AI models with a single API. Let me briefly tell you about it.

Meet AI/ML API ??

AI/ML API is a game-changing platform for developers and SaaS entrepreneurs looking to integrate cutting-edge AI capabilities into their products. It offers a single point of access to over 200 state-of-the-art AI models, covering everything from NLP to computer vision.

Key Features for Developers:

  • Extensive Model Library: 200 pre-trained models for rapid prototyping and deployment. ?
  • Customization Options: Fine-tune models to fit your specific use case. ?
  • Developer-Friendly Integration: RESTful APIs and SDKs for seamless incorporation into your stack. ?️
  • Serverless Architecture: Focus on coding, not infrastructure management. ☁️

Get Started for FREE ($0 US dollars): aimlapi.com ?

Deep Dive into AI/ML API Documentation (very detailed, can't agree more): docs.aimlapi.com ?

Tech Stack Ingredients ?

We'll use TypeScript, Next.js, React, and Tailwind CSS to build and design our AI Sticker Maker platform.

  • TypeScript is just a programming language—but a really great one! ?
  • Next.js is the React Framework for the web. It enables us to create high-quality web applications with the power of React components. ?
  • React is the library for web and native user interfaces. ?️
  • Tailwind CSS is the best for styling—just build whatever you want, seriously. ?

That was just a quick overview of what we're going to use. Feel free to learn more about each of them here:

  • TypeScript: typescriptlang.org ?
  • Next.js: nextjs.org ⏭️
  • React: react.dev ⚛️
  • Tailwind CSS: tailwindcss.com ?️

Cooking Has Started ?

Let's get our hands dirty! First, create a folder. Open your terminal and enter this:

mkdir aiml-tutorial
cd aiml-tutorial

Now, let's create a new Next.js app:

npx create-next-app@latest

It will ask you a few questions:

What is your project named? Here, you should enter your app name. For example: aistickermaker. For the rest of the questions, simply hit enter.

Here's what you'll see:

✔ Would you like to use TypeScript? … No / Yes
✔ Would you like to use ESLint? … No / Yes
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack for `next dev`? … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes

Pro Tip: Feel free to choose Yes or No based on your preferences. I won't judge! ?

Let's open the project with VSCode:

code .

Now, Visual Studio Code should launch directly with this app. Time to start coding! ?

Implementing APIs ?️

First things first, let's create APIs for enhancing the user prompt and generating the sticker. Go to the app folder, then create a new folder called api, and within it, create two new folders: enhancePrompt and generateSticker. For each, create a route.ts file.

The enhancePrompt Endpoint ?‍♂️

Now, let's start with the enhancePrompt endpoint. Open route.ts inside the enhancePrompt folder and enter the following code:

import { NextResponse } from 'next/server';

const systemPrompt = `
You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."
`;

export async function POST(request: Request) {
    try {
        const { userPrompt } = await request.json();
        console.log("/api/enhancePrompt/route.ts userPrompt: ", userPrompt);

        // Make the API call to the external service
          const response = await fetch('https://api.aimlapi.com/chat/completions', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
            },
            body: JSON.stringify({
              model: 'gpt-4o-mini',
              messages: [
                {
                  role: 'system',
                  content: systemPrompt
                },
                {
                  role: 'user',
                  content: userPrompt
                }
              ]
            })
          });

        console.log("response: ", response);

        if (!response.ok) {
            // If the API response isn't successful, return an error response
            return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
        }

        const data = await response.json();
        console.log("data: ", data);

        const assistantResponse = data.choices[0]?.message?.content || "No response available";

        // Return the assistant's message content
        return NextResponse.json({ message: assistantResponse });
    } catch (error) {
        console.error("Error fetching the data:", error);
        return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
    }
}

Here's separated prompt:

You are tasked with enhancing user prompts to generate clear, detailed, and creative descriptions for a sticker creation AI. The final prompt should be imaginative, visually rich, and aligned with the goal of producing a cute, stylized, and highly personalized sticker based on the user's input.

Instructions:

Visual Clarity: The enhanced prompt must provide clear visual details that can be directly interpreted by the image generation model. Break down and elaborate on specific elements of the scene, object, or character based on the user input.

Example: If the user says "A girl with pink hair," elaborate by adding features like "short wavy pink hair with soft, pastel hues."
Style & Theme:

Emphasize that the final output should reflect a cute, playful, and approachable style.
Add terms like "adorable," "cartoonish," "sticker-friendly," or "chibi-like" to guide the output to a lighter, cuter aesthetic.
Include styling prompts like “minimalistic lines,” “soft shading,” and “vibrant yet soothing colors.”
Personalization:

If a reference or context is given, enhance it to make the sticker feel personalized.
Add context-appropriate descriptors like “wearing a cozy blue hoodie,” “soft pink blush on cheeks,” or “a playful expression.”
Expression & Pose:

Where applicable, refine prompts with suggestions about facial expressions or body language. For example, “Smiling softly with big sparkling eyes” or “A cute wink and a slight tilt of the head.”
Background & Accessories:

Optionally suggest simple, complementary backgrounds or accessories, depending on user input. For instance, "A light pastel background with small, floating hearts" or "Holding a tiny, sparkling star."
Colors:

Emphasize the color scheme based on the user's description, making sure it's consistent with a cute, playful style.
Use descriptors like “soft pastels,” “bright and cheerful,” or “warm and friendly hues” to set the mood.
Avoid Overcomplication:

Keep the descriptions short enough to be concise and not overly complex, as the output should retain a sticker-friendly quality.
Avoid unnecessary details that could clutter the design.
Tone and Language:

The tone should be light, imaginative, and fun, matching the playful nature of stickers.

Example:
User Input:
"A girl with pink hair wearing a hoodie."

Enhanced Prompt:
"An adorable girl with short, wavy pink hair in soft pastel hues, wearing a cozy light blue hoodie. She has a sweet smile with big, sparkling eyes, and a playful expression. The sticker style is cartoonish with minimalistic lines and soft shading. The background is a simple light pastel color with small floating hearts, creating a cute and inviting look."

What's Happening Here? ?

  • Importing NextResponse: To handle our HTTP responses smoothly.
  • Defining the POST function: This is where the magic happens when someone hits this endpoint.
  • Fetching the userPrompt: We're grabbing the prompt the user provided.
  • Calling AI/ML API's API: We're making a request to enhance the user's prompt using GPT-4o.
  • Handling Responses: We check if the response is okay, parse the data, and extract the assistant's response.
  • Error Handling: Because nobody likes unhandled errors ruining the party.

Here's an actual example of how the AI enhances the user's prompt. ???

You just entered a prompt:

A cute panda eating ice cream under a rainbow

The AI will enhance it to make it more detailed and visually rich. As a result, you should ger a response like:

An adorable, chibi-like panda with big, sparkling eyes and a joyful expression, savoring a colorful scoop of ice cream. The panda is fluffy and round, with classic black-and-white markings, sitting contentedly. The ice cream cone features vibrant, swirling flavors in pastel pink, mint green, and sunny yellow. Above, a playful, cartoonish rainbow arcs across a soft blue sky, adding a cheerful splash of color. The design is sticker-friendly with minimalistic lines and soft shading, ensuring a cute and delightful aesthetic perfect for capturing the joyful scene.

Alright, let's dive back into the code cauldron and continue cooking up our AI Sticker Maker! ?

The generateSticker Endpoint ?️

So, we've got our enhancePrompt endpoint simmering nicely. Time to spice things up with the generateSticker endpoint. Head over to the api/generateSticker folder and open up route.ts. Replace whatever's in there (probably nothing) with this fresh code:

// api/generateSticker/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
    try {
        const { userPrompt } = await request.json();
        console.log("/api/generateSticker/route.ts userPrompt: ", userPrompt);

        // Make the API call to the external service
        const response = await fetch('https://api.aimlapi.com/images/generations', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${process.env.NEXT_PUBLIC_AIML_API_KEY}`
          },
          body: JSON.stringify({
            provider: 'openai',
            prompt: userPrompt,
            model: 'dall-e-3',
            n: 1,
            quality: 'hd',
            response_format: 'url',
            size: '1024x1024',
            style: 'vivid'
          })
        });

        console.log("response: ", response);

        if (!response.ok) {
            // If the API response isn't successful, return an error response
            return NextResponse.json({ error: "Failed to fetch completion data" }, { status: response.status });
        }

        const data = await response.json();
        console.log("data: ", data);

        const assistantResponse = data.data[0]?.url || "No response available";

        console.log("assistantResponse: ", assistantResponse);

        // Return the assistant's message content
        return NextResponse.json({ message: assistantResponse });
    } catch (error) {
        console.error("Error fetching the data:", error);
        return NextResponse.json({ error: "An error occurred while processing your request." }, { status: 500 });
    }
}

What's Happening Here? ?

  • Importing NextResponse: To handle our HTTP responses smoothly.
  • Defining the POST function: This is where the magic happens when someone hits this endpoint.
  • Fetching the userPrompt: We're grabbing the prompt the user provided.
  • Calling AI/ML API's API: We're making a request to generate an image based on the prompt using DALL·E 3.
  • Handling Responses: We check if the response is okay, parse the data, and extract the image URL.
  • Error Handling: Because nobody likes unhandled errors ruining the party.

Let's try above prompt with panda in action! ?

Here's our cutesy panda sticker! ???

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Other examples ?

Prompt:

A girl with short white grey hair wearing a oversize shirt

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Prompt:

A girl with short black pink hair wearing a oversize pink shirt

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Seems, like really WOW! ?

We need a frontend, GUYS! ?

Building the Frontend ?

Time to put a face on our app! Let's create a user interface where users can input their prompt and get a shiny new sticker.

The page.tsx File ?

Navigate to app/page.tsx and update it with the following code:

// app/page.tsx
'use client';

import Image from "next/image";
import { useState } from 'react';
import { faArrowUp, faDownload, faTimes } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import Notification from './utils/notify';
import { Analytics } from "@vercel/analytics/react"

export default function Home() {
  const [notification, setNotification] = useState(null);  // notification message
  const [loading, setLoading] = useState(false);
  const [prompt, setPrompt] = useState('');
  const [stickerUrl, setStickerUrl] = useState("");

  const loader = () => (
    
  );

  const enhanceUserPrompt = async (prompt: string) => {
    setNotification({ message: 'Enhancing user prompt...', type: 'info' });

    // Make the API call to the /api/enhancePrompt route and return the enhanced prompt
    const response = await fetch('/api/enhancePrompt', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userPrompt: prompt }),
    });

    if (!response.ok) {
      throw new Error('Failed to fetch completion data');
    }

    const data = await response.json();
    return data.message;
  };

  const generateCuteSticker = async (prompt: string) => {
    setNotification({ message: 'Generating cute sticker...', type: 'info' });

    // Make the API call to the /api/generateSticker route and return the generated sticker URL
    const response = await fetch('/api/generateSticker', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ userPrompt: prompt }),
    });

    if (!response.ok) {
      throw new Error('Failed to fetch completion data');
    }

    const data = await response.json();
    return data.message;
  };

    const generateSticker = async () => {
        if (!prompt) return;

        setLoading(true);
        setNotification({ message: 'Processing request...', type: 'info' });

        try {
          // Enhance user prompt
          const enhancedPrompt = await enhanceUserPrompt(prompt);

          if (!enhancedPrompt) {
            setNotification({ message: 'Failed to enhance user prompt.', type: 'error' });
            return;
          }

          // Generate cute sticker
          const sticker = await generateCuteSticker(enhancedPrompt); 

          if (!sticker) {
            setNotification({ message: 'Failed to generate cute sticker.', type: 'error' });
            return;
          }

          setStickerUrl(sticker);
          console.log('Sticker URL:', sticker);
          setNotification({ message: 'Cute sticker generated successfully!', type: 'success' });

        } catch (error) {
          console.error('An unexpected error occurred:', error);
          setNotification({ message: 'An unexpected error occurred.', type: 'error' });
        } finally {
          setLoading(false);
        }
    };

    const handleDownload = () => {
      if (!stickerUrl) return;

      const link = document.createElement('a');
      link.href = stickerUrl;
      link.download = 'cute-sticker.png'; // You can set a default filename
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    };

    const handleClose = () => {
      setStickerUrl("");
      setPrompt("");
    };

    return (
        
{notification && ( setNotification(null)} /> )}

Let's Generate Cutesy AI Sticker!

setPrompt(e.target.value)} placeholder="A girl with short pink hair wearing a oversize hoodie..." className="placeholder:text-[#aeaeae] bg-transparent focus:outline-none text-white outline-none w-full px-4" disabled={loading} />
{/* Modal */} {stickerUrl && (
{/* Download Button */} {/* Close Button */} {/* Sticker Image */}
Generated Sticker
)}
); }

Breaking It Down ?

  • Loader: We are using really simple, but nice loader; three horizontal dots with some nice animaton:
  const loader = () => (
    
  );
  • State Management: Using useState to handle notifications, loading state, the user's prompt, and the sticker URL.
  • Functions:
    • enhanceUserPrompt: Calls our /api/enhancePrompt endpoint to make the user's prompt more... well, prompting.
    • generateCuteSticker: Hits the /api/generateSticker endpoint to get that adorable sticker.
    • generateSticker: Orchestrates the whole process when the user clicks the magic button.
    • handleDownload: Allows the user to download their new sticker.
    • handleClose: Closes the sticker modal.
  • UI Components:
    • Input Field: Where the user types their wildest sticker dreams.
    • Generate Button: Triggers the sticker generation.
    • Modal: Displays the sticker with options to download or close.
    • Notifications: Pops up messages to inform the user what's going on.

A Sprinkle of FontAwesome ?

We're using FontAwesome for icons. Make sure to install it:

npm i --save @fortawesome/fontawesome-svg-core
npm i --save @fortawesome/free-solid-svg-icons
npm i --save @fortawesome/free-regular-svg-icons
npm i --save @fortawesome/free-brands-svg-icons
npm i --save @fortawesome/react-fontawesome@latest

You may also check the FontAwesome documentation for more details. Or search for other icons Search icons.

Handling Notifications ?

Remember that notification component we imported? Let's create it.

Creating the Notification Component ?

Create a new folder called utils inside your app directory. Inside utils, create a file called notify.tsx and paste:

// app/utils/notify.tsx
import React, { useEffect } from 'react';

type NotificationProps = {
  message: string;
  type: 'error' | 'success' | 'info';
  onClose: () => void;
};

const Notification: React.FC = ({ message, type, onClose }) => {
  useEffect(() => {
    const timer = setTimeout(() => {
      onClose();
    }, 3000); // Auto-close after 3 seconds
    return () => clearTimeout(timer);
  }, [onClose]);

  const bgColor = type === 'error' ? 'bg-red-500' : type === 'success' ? 'bg-green-500' : 'bg-blue-500';

  return (
    

{message}

); }; export default Notification;

What's This For? ?

  • Purpose: To display temporary messages to the user, like "Generating cute sticker..." or "An error occurred."
  • Auto-Close Feature: It disappears after 3 seconds, just like my motivation on Monday mornings.
  • Styling: Changes color based on the type of notification.

Configuring Image Domains ?️

Since we're fetching images from OpenAI's servers, Next.js needs to know it's okay to load them. Open up next.config.ts and add:

// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* config options here */
  images: {
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'oaidalleapiprodscus.blob.core.windows.net',
        port: '',
      },
    ],
  },
};

export default nextConfig;

Why Do This? ?‍♂️

Because Next.js is a bit overprotective (like a helicopter parent) and won't load images from external domains unless you specifically allow it. This setting tells Next.js, "It's cool, these images are with me."

Environment Variables ?

Now, before you excitedly run your app and wonder why it's not working, let's set up our environment variables.

Setting Up Your AI/ML API Key ?️

Create a file called .env.local in the root of your project and add:

NEXT_PUBLIC_AIML_API_KEY=your_api_key_here

Replace your_api_key_here with your actual AI/ML API key. If you don't have one, you might need to sign up at AI/ML API and grab it. It's absolutely FREE to get started!

Here's a Quick Tutorial on how to get your API key: How to get API Key from AI/ML API. Quick step-by-step tutorial with screenshots for better understanding.

Warning: Keep this key secret! Don't share it publicly or commit it to Git. Treat it like your Netflix password.

Fire It Up! ?

Time to see this baby in action.

Running the Development Server ?‍♀️

In your terminal, run:

npm run dev

This starts the development server. Open your browser and navigate to http://localhost:3000.

You should see your AI Sticker Maker platform. ?

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Testing It Out ?

  • Enter a Prompt: Something like "A girl with short white grey hair wearing a oversize shirt". Go wild!

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

  • Click the Button: Hit that generate button and watch the magic unfold.
  • Wait for It...: You'll see notifications keeping you posted.
  • Voilà!: Your AI-generated sticker should appear. Bask in its glory.

Building an AI Sticker Maker Platform with AI/ML API, Next.js, React, and Tailwind CSS using OpenAI GPT-and DALL·E odels.

Troubleshooting ?️

  • "Failed to fetch completion data": Double-check your API key and make sure it's set correctly.
  • Images Not Loading: Ensure your next.config.ts file is set up as shown above.
  • App Crashes: Open your console and see what errors pop up. Google is your friend!

Wrapping Up ?

Congratulations! You've just built an AI Sticker Maker that's both fun and functional. Not only did you delve into the world of AI and Next.js, but you also made something that can bring a smile to people's faces.

What's Next? ?

  • Styling: Customize the look and feel. Make it as fabulous or minimalist as you like.
  • Features: Add user accounts, sticker galleries, or even a feature to create sticker packs.
  • Monetization: Integrate Stripe and start charging for premium stickers. Time to make some moolah!

Final Thoughts ?

Building this app was like making a sandwich with layers of tech goodness. We've got AI models as the filling, Next.js as the bread, and a sprinkle of humor as the secret sauce.

Remember, the world is your oyster (or sticker). Keep experimenting, keep building, and most importantly, have fun!

Happy coding! ?

Full implementation available on Github AI Sticker Maker.

It’s Absolutely FREE to get started! Try It Now click

Also check out this tutorial, it's very interesting! Building a Chrome Extension from Scratch with AI/ML API, Deepgram Aura, and IndexedDB Integration

Should you have any questions or need further assistance, don’t hesitate to reach out via email at [email protected].

版本聲明 本文轉載於:https://dev.to/abdibrokhim/building-an-ai-sticker-maker-platform-with-aiml-api-nextjs-react-and-tailwind-css-using-openai-gpt-4o- and-dalle-3-models-46ip?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 網站時間資料集
    網站時間資料集
    您好,我在kaggle上發現了一個網站使用時間的資料集,所以我想找到訪問頁面數與網站總時間之間的比率。 您可以在我的github中找到資料集和程式碼:https://github.com/victordalet/Kaggle_analysis/tree/feat/website_traffic ...
    程式設計 發佈於2024-11-07
  • 如何在 PHP 中以陣列形式從 GET 參數檢索多個值?
    如何在 PHP 中以陣列形式從 GET 參數檢索多個值?
    在PHP 中以數組形式存取值$_GET在PHP 中,$_GET 超全域變數提供了一種存取從Web 表單或URL 查詢發送的數據的方法細繩。但是,目前還不清楚如何以數組形式取得 $_GET 數組中的值。 讓我們考慮一個場景,您想要在URL 中發送「id」參數的多個值:http://link/foo.p...
    程式設計 發佈於2024-11-07
  • 從格式化字串建構日期時如何解決 Internet Explorer 的 NaN 錯誤?
    從格式化字串建構日期時如何解決 Internet Explorer 的 NaN 錯誤?
    修復Internet Explorer 日期構造中的NaN 問題在Web 開發中,使用JavaScript 日期構造函數構造日期可能會在某些瀏覽器中帶來挑戰。特別是在 Internet Explorer (IE) 中,開發人員可能會遇到結果為 NaN 而不是有效日期物件的問題。當嘗試解析「m、d、Y...
    程式設計 發佈於2024-11-07
  • Floyd 演算法如何偵測鍊錶中的迴圈?
    Floyd 演算法如何偵測鍊錶中的迴圈?
    使用 Floyd 演算法檢測鍊錶中的循環確定給定鍊錶是否包含循環在 Java 程式設計中是一項具有挑戰性的任務。當清單中的最後一個節點引用前一個節點而不是空引用時,就會發生循環。 為了有效地偵測循環,開發人員通常採用 Floyd 的循環查找演算法,也稱為龜兔賽跑演算法。該演算法使用兩個引用,一個慢速...
    程式設計 發佈於2024-11-07
  • 如何在不使用 Flash 的情況下使用 JavaScript 在客戶端調整圖像大小?
    如何在不使用 Flash 的情況下使用 JavaScript 在客戶端調整圖像大小?
    使用JavaScript 在客戶端調整圖像大小:開源解決方案在當今的Web 開發環境中,通常需要在客戶端調整圖像大小之前將它們上傳到伺服器。這種方法可以優化影像質量,減少伺服器負載,並透過加快頁面載入時間來改善使用者體驗。 雖然 Flash 是調整圖片大小的常見選項,但許多開發人員寧願避免使用它。幸...
    程式設計 發佈於2024-11-07
  • 通訊:數據獲取模式
    通訊:數據獲取模式
    重大公告! 我開始了我日常的前端系統設計學習之旅。我將在部落格中分享每個模組的見解。所以,這就是開始,還有更多精彩! 在本部落格中,我們將探討前端系統設計所必需的不同資料取得機制,包括短輪詢、長輪詢、WebSocket、伺服器發送事件 (SSE) 和 Webhook。每種技術都滿足向客戶端和伺服...
    程式設計 發佈於2024-11-07
  • #daysofMiva 編碼挑戰日:將 JavaScript 連結到 HTML 檔案。
    #daysofMiva 編碼挑戰日:將 JavaScript 連結到 HTML 檔案。
    嗨,大家好。很抱歉這篇文章遲發了,但遲發總比不發好?無論如何,讓我們深入了解今天的文章。 為什麼要將 Javascript 連結到 HTML 檔案。 JavaScript 是一種在瀏覽器中運行的程式語言,可以操縱網頁的內容、結構和樣式。透過將 JavaScript 檔案連結到 HT...
    程式設計 發佈於2024-11-07
  • 為什麼我的 canvas.toDataURL() 沒有儲存我的圖像?
    為什麼我的 canvas.toDataURL() 沒有儲存我的圖像?
    Resolving Image Saving Issues with canvas.toDataURL()When attempting to utilize canvas.toDataURL() to save&&]When attempting to utilize canvas.toDataU...
    程式設計 發佈於2024-11-07
  • Node.js 中的新增功能
    Node.js 中的新增功能
    TL;DR: 让我们探索 Node.js 22 的主要功能,包括 ECMAScript 模块支持和 V8 引擎更新。此版本引入了 Maglev 编译器和内置 WebSocket 客户端,以增强性能和实时通信。还涵盖了测试、调试和文件系统管理方面的改进。 Node.js 22 将于 10 月进入 LT...
    程式設計 發佈於2024-11-07
  • 了解 MongoDB 的distinct() 操作:實用指南
    了解 MongoDB 的distinct() 操作:實用指南
    MongoDB 的distinct() 操作是一個強大的工具,用於從集合中的指定欄位檢索唯一值。本指南將幫助您了解distinct() 的用途、使用它的原因和時間,以及如何在 MongoDB 查詢中有效地實現它。 什麼是distinct()? distinct() 方法傳回集合或集...
    程式設計 發佈於2024-11-07
  • 為什麼 JavaScript 中的「0」在比較中為 False,而在「if」語句中為 True?
    為什麼 JavaScript 中的「0」在比較中為 False,而在「if」語句中為 True?
    揭開JavaScript 的悖論:為什麼「0」在比較中為假,但在If 語句中為假在JavaScript中,原語" 的行為0」給開發者帶來了困惑。雖然諸如“==”之類的邏輯運算符將“0”等同於假,但“0”在“if”條件下表現為真。 比較悖論代碼下面演示了比較悖論:"0" ...
    程式設計 發佈於2024-11-07
  • GitHub Copilot 有其怪癖
    GitHub Copilot 有其怪癖
    過去 4 個月我一直在將 GitHub Copilot 與我們的生產代碼庫一起使用,以下是我的一些想法: 好的: 解釋複雜程式碼:它非常適合分解棘手的程式碼片段或商業邏輯並正確解釋它們。 單元測試:非常擅長編寫單元測試並快速產生多個基於場景的測試案例。 程式碼片段:它可以輕鬆地為通用用例產生有用...
    程式設計 發佈於2024-11-07
  • 靜態類別或實例化類別:什麼時候應該選擇哪一個?
    靜態類別或實例化類別:什麼時候應該選擇哪一個?
    在靜態類別和實例化類別之間做出選擇:概述在PHP 中設計軟體應用程式時,開發人員經常面臨在使用靜態類別或實例化物件。這個決定可能會對程式的結構、效能和可測試性產生重大影響。 何時使用靜態類別靜態類別適用於物件不具備靜態類別的場景獨特的數據,只需要存取共享功能。例如,用於將 BB 程式碼轉換為 HTM...
    程式設計 發佈於2024-11-07
  • ⚠️ 在 JavaScript 中使用 `var` 的隱藏危險:為什麼是時候繼續前進了
    ⚠️ 在 JavaScript 中使用 `var` 的隱藏危險:為什麼是時候繼續前進了
    关键字 var 多年来一直是 JavaScript 中声明变量的默认方式。但是,它有一些怪癖和陷阱,可能会导致代码出现意外行为。现代替代方案(如 let 和 const)解决了许多此类问题,使它们成为大多数情况下声明变量的首选。 1️⃣ 提升:var 在不知不觉中声明变量! ?解释:...
    程式設計 發佈於2024-11-07
  • PDO::MYSQL_ATTR_INIT_COMMAND 需要「SET CHARACTER SET utf8」嗎?
    PDO::MYSQL_ATTR_INIT_COMMAND 需要「SET CHARACTER SET utf8」嗎?
    在有「PDO::MYSQL_ATTR_INIT_COMMAND」的 PDO 中「SET CHARACTER SET utf8」是否必要? 在PHP 和MySQL 中,「SET NAMES」 utf8」和「SET CHARACTER SET utf8」通常在使用UTF-8 編碼時使用。但是,當使用PD...
    程式設計 發佈於2024-11-07

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3